简体   繁体   English

在js中四舍五入数字的一半

[英]Rounding a half of number in js

Different types of rounding and different result不同类型的舍入和不同的结果

Why is it, I was checking the mathematics rules, where was saying that after 0.5 we are rounding to 1 but in the second operation rounded to 0 and gives me the wrong answer为什么,我正在检查数学规则,其中说在 0.5 之后我们四舍五入到 1 但在第二个操作中四舍五入到 0 并给了我错误的答案

The documentation for Number.prototype.toFixed() describes what's happening in this exact case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed Number.prototype.toFixed() 的文档描述了在这种情况下发生的事情: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

2.34.toFixed(1); // '2.3'
2.35.toFixed(1); // '2.4'; it rounds up
2.55.toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
2.449999999999999999.toFixed(1); // '2.5'
// it rounds up as it's less than NUMBER.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45

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

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