简体   繁体   English

转换浮点数并保持小数位

[英]Convert float and maintain decimal places

I have this values: 我有这个价值观:

var a = 20.0;

document.write(a);                  --> 20
document.write(a.toFixed(2));       --> "20.00"

I want to know if its possible to maintain the decimal places and the variable as float? 我想知道是否有可能将小数位和变量保持为float?

Something like this: 像这样:

20.00

A .0 portion of a number is irrelevant to its value. 数字的.0部分与它的值无关。

Just convert it as you need to when it's time to show the end user. 只需将其转换为需要显示最终用户的时间即可。

The kind of floating point numbers used by JavaScript (IEEE-754) don't maintain a "precision" value of that kind (eg, something to say that " 20.00 " has two zeroes after the decimal, but " 20.000 " has three). JavaScript(IEEE-754)使用的浮点数类型不会保持该类型的“精度”值(例如,要说“ 20.00 ”在小数点后有两个零,而“ 20.000 ”则有三个) 。 Trailing zeroes after the decimal point are not significant. 小数点后的尾随零并不重要。

There is a style of number for doing that in some environments (Java has BigDecimal , C# has decimal ), but nothing built into JavaScript does. 在某些环境中(Java具有BigDecimal ,C#具有decimal ),有一种数字可以做到这一点,但是JavaScript内置没有任何功能。 I believe there's a BigDecimal port to JavaScript out there. 我相信那里有一个JavaScript的BigDecimal端口。

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

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