javascript添加操作返回错误结果 [英] javascript add operation returns bad result

查看:89
本文介绍了javascript添加操作返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的白痴问题:
为什么 javascript 显示 10.2-17 = -6.800000000000001

I've a funny idiotic problem: Why is javascript showing that 10.2 - 17 = -6.800000000000001 ?

在此处找到类似的内容:计算javascript中的减号操作会返回错误的值,但我无法四舍五入。

Found something similar here: Calculate a minus operation in javascript returns a incorrect value but I can't round the numbers.

可以我以某种方式解决了这个问题,但未指定要使用多少个小数? (我实际上有一些结果可以有6-7个小数)

Can I somehow fix this without specifying how many decimals to use? (I actually have some results that can have 6-7 decimals)

推荐答案

浮点运算并不总是精确的。

Floating point arithmetic is not always precise.

特别是没有精确表示10.2作为浮点值,因此存储了最接近的可表示值。此值与10.2会有细微差别。

In particular there is no exact representation of 10.2 as a floating point value, so the nearest representable value is stored instead. This value will be very slightly different from 10.2.

最简单的处理方法是在显示数字时将数字四舍五入到小数点后一位。

The simplest way to handle it is to round the numbers to a certain number of decimal places when you display them.

某些语言的十进制类型可以精确表示10.2。但是:

Some languages have a decimal type that can represent 10.2 exactly. However:


  • JavaScript没有这样的内置类型,因此您必须使用第三方库。

  • 十进制浮点数不能解决所有问题。例如, 0.1 / 0.3 的结果不能完全表示为小数。在显示结果时,可能仍需要将结果四舍五入到小数位数。

  • Javascript has no built in type like this, so you'd have to use a third-party library.
  • Decimal floating point numbers don't solve all problems. For example the result of 0.1 / 0.3 cannot be represented exactly as a decimal. You may still need to round results to a certain number of decimal places when you display them.

这篇关于javascript添加操作返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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