如何阻止parseFloat()从零中删除到十进制右边 [英] How do I stop parseFloat() from stripping zeroes to right of decimal
本文介绍了如何阻止parseFloat()从零中删除到十进制右边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,我用来从字符串中删除不需要的字符(定义为货币符号),然后将值作为数字返回。返回值时,我正在进行以下调用:
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);
我遇到的问题是,当x ==0.00时,我希望得到0.00(带有两位小数的浮点数)。我得到的只是0。
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.
我也尝试了以下内容:
返回parseFloat(x).toFixed(2);
并且仍然只返回0。我错过了什么吗?任何帮助将不胜感激。
and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.
谢谢!!
推荐答案
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));
这篇关于如何阻止parseFloat()从零中删除到十进制右边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文