Javascript 使用Javascript或Jquery将整数转换为精度为2的浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11685253/
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
converting integer to float with precision 2 using Javascript or Jquery
提问by teenu
I want to convert the integer to floating number with precision 2. ie. -
我想将整数转换为精度为 2 的浮点数。即。——
11 => 11.00
11 => 11.00
45 => 45.00
45 => 45.00
Please help me.
请帮我。
Thank you.
谢谢你。
回答by user1236048
var num = 10;
var result = num.toFixed(2);
回答by Yash Rahurikar
This a very common problem I see someone has already answered, I want to add to it, if you want to further use the number after conversion for calculations Try this in console
这是一个很常见的问题,我看到有人已经回答了,我想补充一下,如果您想进一步使用转换后的数字进行计算,请在控制台中尝试此操作
a = 10.2222;
typeof a /*"number"*/
a /*10.2222*/
b = parseFloat(b).toFixed(2);
typeof b /*"String"*/
b /*"10.22"*/
c = parseFloat(c)
typeof c /*"number"*/
c /*10.22*/
Explanation is-
解释是——
toFixed() method outputs a string variable
but if you want to further use the value of b as a 'number'
you will have to,
c = parseFloat(b)
typeof c
// "number"
回答by Abdus Salam Azad
Just add toFixed(2)
here with your variable.
只需在toFixed(2)
此处添加您的变量即可。