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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:44:03  来源:igfitidea点击:

converting integer to float with precision 2 using Javascript or Jquery

javascriptjquery

提问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 Esailija

Use .toFixed:

使用.toFixed

var num = 45;
num.toFixed(2); //"45.00"

回答by user1236048

回答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)此处添加您的变量即可。