简体   繁体   English

在javascript中格式化小数

[英]formatting decimals in javascript

i want to format a number to max of 2 decimals in javascript. 我想在javascript中将数字格式化为最多2位小数。 i see that there is: 我看到有:

toFixed(2)

but this seems like it would ALWAYS do 2 decimals. 但这似乎总是会做2位小数。 i want something that would take: 100.1223334 and convert it to 100.12 but i want this function to convert 100.5 to just 100.5 (since < 2 decimal digits) 我想要的东西:100.1223334并将其转换为100.12但我希望此功能将100.5转换为100.5(因为<2位小数)

whats is the best way of doing this in javascript. 什么是在javascript中执行此操作的最佳方式。

Use Math.round(number * 100) / 100 . 使用Math.round(number * 100) / 100

For example, 100.1223 becomes 10012.23, which is rounded to the nearest integer (10012) and then divided by 100 to get 100.12. 例如,100.1223变为10012.23,四舍五入到最接近的整数(10012),然后除以100得到100.12。

Use Math.round(number) . 使用Math.round(number) This will round off the number to maximum 2 decimals. 这会将数字四舍五入到最多2位小数。

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

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