JavaScript浮动减法 [英] Javascript float subtract

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

问题描述

我想知道如何在JavaScript中减去两个负浮点数。我试过:

  alert(-0.2-0.1); 

,结果是 -0.30000000000000004 。难道我做错了什么?我得做什么才能得到 -0.3

解决方案

否,你的代码没有问题,大多数小数不能完全代表二进制
,使用

  number.toFixed x)

其中 x 小数点是你想要的, number 是减法的结果。


I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

alert(-0.2-0.1);

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

解决方案

No, nothing wrong with your code, most decimal fractions cannot be represented exactly in binary, use

number.toFixed(x)

Where x is the number of decimals you want and number is the result of the subtraction.

这篇关于JavaScript浮动减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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