将 JavaScript 字符串变量转换为十进制/金钱
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6095795/
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
convert a JavaScript string variable to decimal/money
提问by Varada
How can we convert a JavaScript string variable to decimal?
我们如何将 JavaScript 字符串变量转换为十进制?
Is there a function such as:
有没有这样的功能:
parseInt(document.getElementById(amtid4).innerHTML)
回答by lonesomeday
Yes -- parseFloat
.
是的—— parseFloat
。
parseFloat(document.getElementById(amtid4).innerHTML);
For formattingnumbers, use toFixed
:
要格式化数字,请使用toFixed
:
var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
num
is now a string with the number formatted with two decimal places.
num
现在是一个字符串,其数字格式为两位小数。
回答by KooiInc
You can also use the Number
constructor/function (no need for a radix and usable for both integers and floats):
您还可以使用Number
构造函数/函数(不需要基数并且可用于整数和浮点数):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use +
for conversion
或者像 Andy E 在评论中所说的那样,您可以+
用于转换
+'09'; /=> 9
+'09.0987'; /=> 9.0987
回答by Sanjay
This works:
这有效:
var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);
回答by zloctb
var formatter = new Intl.NumberFormat("ru", {
style: "currency",
currency: "GBP"
});
alert( formatter.format(1234.5) ); // 1 234,5 £
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
回答by dondrzzy
It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.
依靠 javascript 函数来比较和玩数字是相当冒险的。在 javascript (0.1+0.2 == 0.3) 中,由于舍入错误,将返回 false。使用 math.js 库。
回答by sidonaldson
回答by Tushar Sagar
An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.
一个简单的简写方法是使用 +x 它保持符号和十进制数完好无损。另一种选择是使用 parseFloat(x)。parseFloat(x) 和 +x 之间的区别在于空白字符串 +x 返回 0,而 parseFloat(x) 返回 NaN。