Javascript 如何阻止 parseFloat() 将零剥离到小数点右侧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4868556/
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
How do I stop parseFloat() from stripping zeroes to right of decimal
提问by Chris K.
I have a function that I'm using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am making the following call:
我有一个函数,用于从字符串中删除不需要的字符(定义为货币符号),然后将值作为数字返回。返回值时,我进行了以下调用:
return parseFloat(x);
return parseFloat(x);
The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.
我遇到的问题是,当 x == "0.00" 时,我希望得到 0.00(带有两位小数的浮点数)。我得到的只是0。
I've also tried the following:
我还尝试了以下方法:
return parseFloat(x).toFixed(2);
return parseFloat(x).toFixed(2);
and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.
并且仍然简单地返回 0。我错过了什么吗?任何帮助将不胜感激。
Thank you!!
谢谢!!
采纳答案by Gergely Fehérvári
simple:
简单的:
function decimalPlaces(float,length) {
ret = "";
str = float.toString();
array = str.split(".");
if(array.length==2) {
ret += array[0] + ".";
for(i=0;i<length;i++) {
if(i>=array[1].length) ret += '0';
else ret+= array[1][i];
}
}
else if(array.length == 1) {
ret += array[0] + ".";
for(i=0;i<length;i++) {
ret += '0'
}
}
return ret;
}
document.write(decimalPlaces(3.123,6));
回答by Ted Hopp
parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:
parseFloat() 将字符串转换为浮点数。这是一个二进制值,而不是十进制表示,因此小数点右边的零数的概念甚至不适用;这一切都取决于它如何重新格式化为字符串。关于 toFixed,我建议将浮点数转换为数字:
new Number(parseFloat(x)).toFixed(2);
回答by Victor
this should work:
这应该有效:
return parseFloat(x).toFixed(2);
you can test it by running this in firebug:
您可以通过在 firebug 中运行它来测试它:
var x = '0.00';
alert(parseFloat(x).toFixed(2));
回答by Rob Sanders
For future readers, I had this issue as I wanted to parse the onChange
value of a textField into a float, so as the user typed I could update my model.
对于未来的读者,我遇到了这个问题,因为我想将onChange
textField的值解析为浮点数,以便在用户输入时我可以更新我的模型。
The problem was with the decimal place and values such as 12.120
would be parsed as 12.12
so the user could never enter a value like 12.1201
.
问题在于小数位和诸如此类的值12.120
将被解析为12.12
因此用户永远无法输入诸如12.1201
.
The way I solved it was to check to see if the STRINGvalue contained a decimal place and then split the string at that decimal and then count the number of characters after the place and then format the float with that specific number of places.
我解决它的方法是检查STRING值是否包含小数位,然后在该小数点处拆分字符串,然后计算该位后的字符数,然后使用该特定位数格式化浮点数。
To illustrate:
为了显示:
const hasDecimal = event.target.value.includes(".");
const decimalValue = (hasDecimal ? event.target.value.split(".") : [event.target.value, ""])[1];
const parsed = parseFloat(event.target.value).toFixed(decimalValue.length);
const value = isNaN(parsed) ? "" : parsed;
onEditValue(value);
回答by Sagynbek Kenzhebaev
Here is dynamic version of floatParser for those who need
这是 floatParser 的动态版本,供需要的人使用
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}