Javascript浮点减法 [英] Javascript float subtract

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

问题描述

我想知道如何在 javascript 中减去两个负浮点数.我试过了:

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

alert(-0.2-0.1);

结果是-0.30000000000000004.难道我做错了什么?我需要做什么才能获得 -0.3 ?

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)

x 是你想要的小数位数,number 是减法的结果.

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

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

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