Javascript 在 React Native 中使用小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34410655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:18:14  来源:igfitidea点击:

Using Decimals in React Native

javascriptreact-native

提问by Nimila Hiranya

I have a state as value: 10.00and once I update it with some operation and add it to a <Text>the ".00" part gets trimmed off. If it was a value like 10.50, it'll be displayed as 10.5

我有一个状态value: 10.00,一旦我用一些操作更新它并将它添加到<Text>“.00”部分就会被修剪掉。如果它是一个像 10.50 这样的值,它将显示为 10.5

This is a issue as I want to display currency values. How to handle this?

这是一个问题,因为我想显示货币价值。如何处理?

回答by Nimila Hiranya

Found the answer. To have the value with decimal values, use toFixed()method.

找到了答案。要具有十进制值的值,请使用toFixed()方法。

Example:

例子:

var value = 10;
value = value.toFixed(2);
this.setState({subTotal: value});

The output would be: 10.00

输出将是:10.00

回答by Gaurav Vanani

here is another solution you can also try, what i need is don't allow to enter more than 2 decimal digits (after decimal point) and also shouldn't allow more than two decimal points or any other character.

这是您也可以尝试的另一种解决方案,我需要的是不允许输入超过 2 个十进制数字(小数点后),也不应允许超过两个小数点或任何其他字符。

    ConTwoDecDigit=(digit)=>{
      return digit.indexOf(".")>0?
              digit.split(".").length>=2?
               digit.split(".")[0]+"."+digit.split(".")[1].substring(-1,2)
              : digit
             : digit
    }
    <TextInput 
       value={this.state.salary}
       onChangeText={value => this.setState({ salary: this.ConTwoDecDigit(value) })} 
      keyboardType={'decimal-pad'}
    />

回答by Pravin S.

If you don't want to show unnecessary zero after decimal points.

如果您不想在小数点后显示不必要的零。

_CalculateValue(value) {
    if((value * 100.0).toFixed(3)<value * 100.0)
    {
        return (value * 100.0).toFixed(3)
    }
    return value * 100.0
}

Output:

输出:

10
17.890
12
783.120
56.009