简体   繁体   English

如何为 JavaScript 中的数字添加小数?

[英]How to add decimals to a number in JavaScript?

I am currently trying to add two decimal places to the end of the number 1000 (I need it to be 1000.00)我目前正在尝试在数字 1000 的末尾添加两位小数(我需要它是 1000.00)

I am trying to use: parseFloat(1000).toFixed(2) but it keeps returning a string.我正在尝试使用: parseFloat(1000).toFixed(2) 但它一直返回一个字符串。 When I do parseFloat((1000).toFixed(2)) it returns a number, but gets rid of the decimal places.当我执行 parseFloat((1000).toFixed(2)) 时,它会返回一个数字,但会去掉小数位。 Is there a way to convert the number 1000 into the number 1000.00 without returning a string?有没有办法在不返回字符串的情况下将数字 1000 转换为数字 1000.00?

Try to use .toLocaleString()尝试使用.toLocaleString()

var n = 1000;
var nWithZerto = n.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});

Since, Javascript treat both integer and, decimal as Number, so it doesn't matter in calculation.由于 Javascript 将 integer 和十进制都视为数字,因此在计算中并不重要。

But, if you are printing it then only you require formatting and it can be done as (1000).toFixed(2)-> string.但是,如果您要打印它,那么只有您需要格式化,它可以作为 (1000).toFixed(2)-> 字符串来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM