简体   繁体   English

JavaScript:toFixed(...) 方法的缺点

[英]JavaScript: Downsides of toFixed(...) method

In my programs, I need "float" numbers rounded to the nearest two decimal digits, and after some research I decided to use toFixed(..) for this purpose, like shown in the example below.在我的程序中,我需要四舍五入到最接近的两位十进制数字的“浮点”数字,经过一些研究,我决定为此目的使用 toFixed(..),如下例所示。 What are the downsides of using toFixed()?使用 toFixed() 的缺点是什么? Does it work in all browsers correctly?它在所有浏览器中都能正常工作吗? If not, what are some cases that it does not work correctly?如果不是,在哪些情况下它不能正常工作?

var numb = 123.23454; 
numb = +numb.toFixed(2);

Provided the fixed decimal point behavior is satisfactory, there's nothing wrong with using toFixed . 只要固定的小数点行为令人满意,则使用toFixed没错。 According to Mozilla's Developer Documentation , this method was implemented in JavaScript 1.5, which was released in 2000, so you'll see compatibility with virtually every modern browser, including IE6+. 根据Mozilla的开发人员文档 ,此方法是在2000年发布的JavaScript 1.5中实现的,因此您将看到与几乎所有现代浏览器(包括IE6 +)的兼容性。

edit : Ah, and if you weren't aware, toFixed turns a number into a string, useful for doing, well, String things. 编辑 :嗯,如果您不知道, toFixed会将数字转换为字符串,这对完成String事情很有用。 If that was not your intended behavior, look here for an SO question on the Math.round method. 如果这不是您想要的行为,请在此处查找有关Math.round方法的SO问题。

Applause to this reference source , ToFixed() doesn't handle corner cases very well.这个参考源鼓掌, ToFixed()不能很好地处理极端情况。

 const value = 1.005; console.log(value.toFixed(2)) // expect 1.01, return 1.00

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

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