简体   繁体   English

如何避免或解决下限函数和错误表示的整数?

[英]How do I avoid or work around the floor function and incorrectly represented integers?

So I am trying to take a number that can be in any positive form and cut it to two decimal places. 因此,我尝试采用可以采用任何正数形式的数字并将其减少到两位小数。 So for example I have an input of 145.26. 例如,我的输入为145.26。 However in my code this is being rounded down to 145.19. 但是在我的代码中,此值已四舍五入到145.19。 Here is the code I am using: 这是我正在使用的代码:

        var multiplier = 100;
        var adjustedNum = input * multiplier;
        var truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);
        var fixedResult =  truncatedNum / multiplier;

So basically my 'input' should become 145200. However it is actually becoming 145199.9999995 or something to that effect. 因此,基本上我的“输入”应该变成145200。但是实际上它变成了145199.9999995或类似的值。 This is causing the Math.floor method to round it down. 这导致Math.floor方法将其四舍五入。 Is there any way to workaround or avoid this? 有什么办法可以解决或避免这种情况?

Multiply the number by an additional factor of 10 to round it. 将数字乘以10即可得出整数。 Then divide it by 10 to apply the floor or ceil . 然后将其除以10即可涂抹floorceil

var multiplier = 100;
var adjustedNum = Math.round(input * multiplier * 10);
var truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum/10);
var fixedResult =  truncatedNum / multiplier;

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

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