Javascript舍入问题 [英] Javascript rounding issue

查看:80
本文介绍了Javascript舍入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中遇到了一个奇怪的数学/舍入问题。

I've got a weird maths/rounding problem in Javascript.

下面的代码片段是我正在运行的代码的一个非常基本的例子。显然这不是这个确切的代码,但是我从一个文本框中取一个小数值,计算一个百分比并从一个文件中拿走它。

The snippet below is a very basic example of the code I'm running. Obviously it's not this exact code, but I'm taking a decimal value from a text box, working out a percentage and taking this away from one.

var ten = "10";
var eight = "8";

alert(1 - (eight/ten));

问题是答案是0.2,但计算结果返回0.1999999999999996。然而,如果我做1 +(八/十)1.8返回。发生了什么?

The problem is the answer is 0.2 but the calculation returns 0.1999999999999996. Yet if I do 1 + (eight/ten) 1.8 is returned. What is going on?

推荐答案

欢迎来到浮点数世界!

计算机实际上不使用十进制数 - 即基数十的数字,我们在正常生活中使用它们的方式。它们使用二进制数,包括浮点数。它们也以二进制表示,这意味着小数位数并不总是浮点数的有意义属性。

Computers don't actually work with decimal numbers--i.e. numbers in base ten, the way we use them in normal life. They work with binary numbers, and that includes floating-point numbers. They're represented in binary as well, and that means that "number of decimal places" is not always a meaningful property of a floating-point number.

例如,浮点数不能精确地表示0.1,如果您尝试在代码中使用它,您将获得类似0.1000000001的内容。您获得的确切值因实现而异,并且无法通过减去差异来纠正,因为计算机无法判断是否存在差异 - 这种差异可以达到0.1。

For instance, a floating-point number cannot exactly represent 0.1, and you'll get something like 0.1000000001 if you try to use it in your code. The exact value you get varies by implementation, and is not correctable by subtracting the difference, as the computer can't tell that there is a difference--that's as close as it can get to 0.1.

(从我之前的答案。)

这篇关于Javascript舍入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆