最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to show numbers with 2 Decimal Places in React Native - Stack Overflow

programmeradmin1浏览0评论

I am creating a calculator app to help with decimals and would like something to two decimal places like below:

number     output
------     -------
1          1.00
1.446      1.45
1.567      1.57

I have tried using toFixed(2) but I get an error as I'm using maths and not strings.

I've also tried using toPrecision(4) but I also get an error

Any help would be really appreciated.

import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity, Vibration} from 'react-native';
import {useState} from 'react';
import { Entypo } from '@expo/vector-icons';

export default function App() {
  const [darkMode, setDarkMode] = useState(false);
  const [currentNumber, setCurrentNumber] = useState('');
  const [lastNumber, setLastNumber] = useState('');

  const buttons = ['C', 'DEL', '/', 7, 8, 9, '*', 4, 5, 6, '-', 1, 2, 3, '+', 0, '.', '=']

  function calculator() {
    
    let lastArr = currentNumber[currentNumber.length-1];
    
    if(lastArr === '/' || lastArr === '*' || lastArr === '-' || lastArr === '+' || lastArr === '.') {
      setCurrentNumber(currentNumber)
      return
    }
    else {
      let result = eval(currentNumber).toString();
      setCurrentNumber(result)
      return
    }
  }

  function handleInput(buttonPressed) {
    if(buttonPressed  === '+' || buttonPressed === '-' || buttonPressed === '*' || buttonPressed === '/') {
      Vibration.vibrate(35);
      setCurrentNumber(currentNumber + buttonPressed)
      return
    }
    else if (buttonPressed === 1 || buttonPressed === 2 || buttonPressed === 3 || buttonPressed === 4 || buttonPressed === 5 ||
            buttonPressed === 6 || buttonPressed === 7 || buttonPressed === 8 || buttonPressed === 9 || buttonPressed === 0 || buttonPressed === '.' ) {
      Vibration.vibrate(35);
    }
    switch(buttonPressed) {
      case 'DEL':
        Vibration.vibrate(35);
        setCurrentNumber(currentNumber.substring(0, (currentNumber.length - 1)))
        return
      case 'C':
        Vibration.vibrate(35);
        setLastNumber('')
        setCurrentNumber('')
        return 
      case '=':
        Vibration.vibrate(35);
        setLastNumber(currentNumber + '=')
        calculator()
        return
    }
    setCurrentNumber(currentNumber + buttonPressed)
  }

I am creating a calculator app to help with decimals and would like something to two decimal places like below:

number     output
------     -------
1          1.00
1.446      1.45
1.567      1.57

I have tried using toFixed(2) but I get an error as I'm using maths and not strings.

I've also tried using toPrecision(4) but I also get an error

Any help would be really appreciated.

import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity, Vibration} from 'react-native';
import {useState} from 'react';
import { Entypo } from '@expo/vector-icons';

export default function App() {
  const [darkMode, setDarkMode] = useState(false);
  const [currentNumber, setCurrentNumber] = useState('');
  const [lastNumber, setLastNumber] = useState('');

  const buttons = ['C', 'DEL', '/', 7, 8, 9, '*', 4, 5, 6, '-', 1, 2, 3, '+', 0, '.', '=']

  function calculator() {
    
    let lastArr = currentNumber[currentNumber.length-1];
    
    if(lastArr === '/' || lastArr === '*' || lastArr === '-' || lastArr === '+' || lastArr === '.') {
      setCurrentNumber(currentNumber)
      return
    }
    else {
      let result = eval(currentNumber).toString();
      setCurrentNumber(result)
      return
    }
  }

  function handleInput(buttonPressed) {
    if(buttonPressed  === '+' || buttonPressed === '-' || buttonPressed === '*' || buttonPressed === '/') {
      Vibration.vibrate(35);
      setCurrentNumber(currentNumber + buttonPressed)
      return
    }
    else if (buttonPressed === 1 || buttonPressed === 2 || buttonPressed === 3 || buttonPressed === 4 || buttonPressed === 5 ||
            buttonPressed === 6 || buttonPressed === 7 || buttonPressed === 8 || buttonPressed === 9 || buttonPressed === 0 || buttonPressed === '.' ) {
      Vibration.vibrate(35);
    }
    switch(buttonPressed) {
      case 'DEL':
        Vibration.vibrate(35);
        setCurrentNumber(currentNumber.substring(0, (currentNumber.length - 1)))
        return
      case 'C':
        Vibration.vibrate(35);
        setLastNumber('')
        setCurrentNumber('')
        return 
      case '=':
        Vibration.vibrate(35);
        setLastNumber(currentNumber + '=')
        calculator()
        return
    }
    setCurrentNumber(currentNumber + buttonPressed)
  }
Share Improve this question edited Feb 22, 2022 at 11:01 Frankinstyyn asked Feb 21, 2022 at 21:19 FrankinstyynFrankinstyyn 2131 gold badge4 silver badges15 bronze badges 1
  • Please revise your post title to ask a clear, specific question. Don't tack on tags. See How to Ask. – isherwood Commented Feb 21, 2022 at 22:17
Add a ment  | 

3 Answers 3

Reset to default 5

From your question it is not clear where you want to perform the conversion. However, this should get you on the right track.

Both toFixed() and toPrecision() return a string representing a number. It's clear that you can't use the string for further calculations. In order to do so, use parseFloat() to get the floating point number from the string.

const floatingPointNumber = 1.567;
parseFloat(floatingPointNumber.toFixed(2));
parseFloat(floatingPointNumber.toPrecision(3));

Regarding toFixed() and toPrecision(), they actually perform the same operation but the first gives n decimal places while the latter gives n digits (see this question).

try this, may be helps you;

  function floatTwoDecFromString(value: string) {
    let newValue = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
    newValue =
      newValue.indexOf('.') !== -1
        ? newValue.slice(0, newValue.indexOf('.') + 3)
        : newValue;
    return newValue;
  }

I understand that you are trying to round and not just clip to decimal places. You could use Math.round. While it rounds to the nearest int, you could use this trick to round decimals:

const roundToHundredths = num=>{
  let roundedNum = Math.round(num*100)/100
  // force 2 decimal places
  return roundedNum.toFixed(2);
}

Keep in mind that the value is now a string. Use parseFloat if other calculations have to be done

发布评论

评论列表(0)

  1. 暂无评论