在JavaScript中舍入到最接近的十进制小数 [英] Rounding to the nearest hundredth of a decimal in JavaScript

查看:78
本文介绍了在JavaScript中舍入到最接近的十进制小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中使用变量来表示数字。
以下是我的代码示例:

I'm doing simple math in JavaScript using variables to represent the numbers. Here is an example of my code:

var ones = 0;
var fives = 0;
function results (){
    _fives = (fives * 5);
    var res = (_fives + ones);
    document.innerHTML = res;
}

这不是完整的代码,但基本上我让用户输入从1美分硬币到100美元钞票的账单和硬币数量。该代码将账单金额乘以账单金额。这是没有问题的工作就好......
由于某些原因我的一些结果显示小数像1.899999999997,不知道这是怎么回事。

This isn't the full code but basically I'm having the user enter the amount of bills and coins from 1 cent coins up to $100 bills. The code multiplies the amount of bills to the amount the bill is worth. This is no problem works just fine... For some reason on some of my results it shows a decimal like 1.899999999997 not sure how this is happening.

有没有办法改变它,所以它舍入到最接近的十进制小数?

Is there a way to change this so it round to the nearest hundredth of a decimal?

例如,它显示1.89999999997而不是显示1.90
in现实这不是一个大问题。这是个人的事情,我可以自己解决这个问题但是学习如何做以备将来参考会很好。

For example instead of it showing 1.89999999997 it would just show 1.90 in reality this isn't a big issue. This is a personal thing that I can just round it myself however it would be nice to learn how to do this for future reference.

推荐答案

UPDATE :MDN实际上有一个十进制舍入的一个很好的例子,可以避免浮点不准确。根据OP,他们的方法可以修改为总是向上舍入。

UPDATE: MDN actually has a great example of decimal rounding that avoids floating point inaccuracies. Their method can be modified to always round up, based on the OP.

//to round to n decimal places
function round(num, places) {
    var multiplier = Math.pow(10, places);
    return Math.round(num * multiplier) / multiplier;
}

编辑:我没看过这个问题完全。由于我们正在谈论货币,我们可能想要将其四舍五入:

EDIT: I didn't read the question completely. Since we're talking currency, we probably want to round it up:

//to round up to two decimal places
function money_round(num) {
    return Math.ceil(num * 100) / 100;
}

这篇关于在JavaScript中舍入到最接近的十进制小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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