Javascript 四舍五入至小数点后 2 位(仅在必要时)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11832914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:17:17  来源:igfitidea点击:

Round to at most 2 decimal places (only if necessary)

javascriptroundingdecimal-point

提问by stinkycheeseman

I'd like to round at most 2 decimal places, but only if necessary.

我最多四舍五入小数点后两位,但仅限于必要时

Input:

输入:

10
1.7777777
9.1

Output:

输出:

10
1.78
9.1

How can I do this in JavaScript?

我怎样才能在 JavaScript 中做到这一点?

回答by Brian Ustas

Use Math.round(num * 100) / 100

Math.round(num * 100) / 100

Edit:to ensure things like 1.005 round correctly, we use

编辑:为了确保 1.005 回合正确,我们使用

Math.round((num + Number.EPSILON) * 100) / 100

Math.round((num + Number.EPSILON) * 100) / 100

回答by A Kunin

If the value is a text type:

如果值为文本类型:

parseFloat("123.456").toFixed(2);

If the value is a number:

如果值为数字:

var numb = 123.23454;
numb = numb.toFixed(2);

There is a downside that values like 1.5 will give "1.50" as the output. A fix suggested by @minitech:

有一个缺点,像 1.5 这样的值会给出“1.50”作为输出。@minitech 建议的修复:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

It seems like Math.roundis a better solution. But it is not!In some cases it will NOTround correctly:

似乎Math.round是一个更好的解决方案。但事实并非如此!在某些情况下,它不会正确舍入:

Math.round(1.005 * 1000)/1000 // Returns 1 instead of expected 1.01!

toFixed() will also NOTround correctly in some cases (tested in Chrome v.55.0.2883.87)!

toFixed()在某些情况下也不会正确舍入(在 Chrome v.55.0.2883.87 中测试)!

Examples:

例子:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

I guess, this is because 1.555 is actually something like float 1.55499994 behind the scenes.

我想,这是因为 1.555 在幕后实际上类似于 float 1.55499994 。

Solution 1is to use a script with required rounding algorithm, for example:

解决方案 1是使用具有所需舍入算法的脚本,例如:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy?p=preview

https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy?p=preview

NOTE:This is not a universal solution for everyone. There are several different rounding algorithms, your implementation can be different, depends on your requirements. https://en.wikipedia.org/wiki/Rounding

注意:这不是适用于所有人的通用解决方案。有几种不同的舍入算法,您的实现可能会有所不同,这取决于您的要求。https://en.wikipedia.org/wiki/Rounding

Solution 2is to avoid front end calculations and pull rounded values from the backend server.

解决方案 2是避免前端计算并从后端服务器提取四舍五入的值。

回答by MarkG

You can use

您可以使用

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.

我在MDN上找到了这个。他们的方法避免了提到的1.005 的问题。

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57

回答by Lavamantis

MarkG's answer is the correct one. Here's a generic extension for any number of decimal places.

MarkG 的答案是正确的。这是任意数量的小数位的通用扩展。

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

Usage:

用法:

var n = 1.7777;    
n.round(2); // 1.78

Unit test:

单元测试:

it.only('should round floats to 2 places', function() {

  var cases = [
    { n: 10,      e: 10,    p:2 },
    { n: 1.7777,  e: 1.78,  p:2 },
    { n: 1.005,   e: 1.01,  p:2 },
    { n: 1.005,   e: 1,     p:0 },
    { n: 1.77777, e: 1.8,   p:1 }
  ]

  cases.forEach(function(testCase) {
    var r = testCase.n.round(testCase.p);
    assert.equal(r, testCase.e, 'didn\'t get right number');
  });
})

回答by cronvel

You should use:

你应该使用:

Math.round( num * 100 + Number.EPSILON ) / 100

No one seems to be aware of Number.EPSILON.

似乎没有人意识到Number.EPSILON

Also it's worth noting that this is not a JavaScript weirdnesslike some people stated.

另外值得注意的是,这并不是一些人所说的JavaScript 怪癖

That is simply the way floating point numbers works in a computer.Like 99% of programming languages, JavaScript doesn't have home madefloating point numbers; it relies on the CPU/FPU for that. A computer uses binary, and in binary, there isn't any numbers like 0.1, but a mere binary approximation for that. Why? For the same reason than 1/3 cannot be written in decimal: its value is 0.33333333... with an infinity of threes.

这就是浮点数在计算机中的工作方式。像 99% 的编程语言一样,JavaScript 没有自制的浮点数;它依赖于 CPU/FPU。计算机使用二进制,在二进制中,没有像 那样的任何数字0.1,而只是一个二进制近似值。为什么?出于同样的原因,1/3 不能写成十进制:它的值是 0.33333333... 无穷大的三个。

Here come Number.EPSILON. That number is the difference between 1 and the nextnumber existing in the double precision floating point numbers. That's it: There is no number between 1and 1 + Number.EPSILON.

来吧Number.EPSILON。该数字是 1 与双精度浮点数中存在的下一个数字之间的差值。就是这样:1和 1 +之间没有数字Number.EPSILON

EDIT:

编辑:

As asked in the comments, let's clarify one thing: adding Number.EPSILONis relevant only when the value to round is the result of an arithmetic operation, as it can swallow some floating point error delta.

正如评论中所问,让我们澄清一件事:Number.EPSILON仅当要舍入的值是算术运算的结果时,相加才相关,因为它可以吞下一些浮点误差增量。

It's not useful when the value comes from a direct source (e.g.: literal, user input or sensor).

当值来自直接来源(例如:文字、用户输入或传感器)时,它没有用。

EDIT (2019):

编辑(2019):

Like @maganap and some peoples have pointed out, it's best to add Number.EPSILONbefore multiplying:

就像@maganap 和一些人指出的那样,最好Number.EPSILON在乘法之前添加:

Math.round( ( num + Number.EPSILON ) * 100 ) / 100

EDIT (december 2019):

编辑(2019 年 12 月):

Lately, I use a function similar to this one for comparing numbers epsilon-aware:

最近,我使用了一个类似于这个函数来比较数字 epsilon-aware:

const ESPILON_RATE = 1 + Number.EPSILON ;
const ESPILON_ZERO = Number.MIN_VALUE ;

function epsilonEquals( a , b ) {
  if ( Number.isNaN( a ) || Number.isNaN( b ) ) {
    return false ;
  }
  if ( a === 0 || b === 0 ) {
    return a <= b + EPSILON_ZERO && b <= a + EPSILON_ZERO ;
  }
  return a <= b * EPSILON_RATE && b <= a * EPSILON_RATE ;
}

My use-case is an assertion + data validation libI'm developing for many years.

我的用例是我开发多年的断言 + 数据验证库

In fact, in the code I'm using ESPILON_RATE = 1 + 4 * Number.EPSILONand EPSILON_ZERO = 4 * Number.MIN_VALUE(four times the epsilon), because I want an equality checker loose enough for cumulating floating point error.

事实上,在代码中我使用ESPILON_RATE = 1 + 4 * Number.EPSILONEPSILON_ZERO = 4 * Number.MIN_VALUE(四倍小量),因为我想要一个平等的检查不够宽松累计浮点错误。

So far, it looks perfect for me. I hope it will help.

到目前为止,它对我来说看起来很完美。我希望它会有所帮助。

回答by Gourav Singla

One can use .toFixed(NumberOfDecimalPlaces).

一个可以使用.toFixed(NumberOfDecimalPlaces)

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23

回答by Mark Amery

This question is complicated.

这个问题很复杂。

Suppose we have a function, roundTo2DP(num), that takes a float as an argument and returns a value rounded to 2 decimal places. What should each of these expressions evaluate to?

假设我们有一个函数,roundTo2DP(num),它将一个浮点数作为参数并返回一个四舍五入到小数点后两位的值。这些表达式中的每一个都应该评估什么?

  • roundTo2DP(0.014999999999999999)
  • roundTo2DP(0.0150000000000000001)
  • roundTo2DP(0.015)
  • roundTo2DP(0.014999999999999999)
  • roundTo2DP(0.0150000000000000001)
  • roundTo2DP(0.015)

The 'obvious' answer is that the first example should round to 0.01 (because it's closer to 0.01 than to 0.02) while the other two should round to 0.02 (because 0.0150000000000000001 is closer to 0.02 than to 0.01, and because 0.015 is exactly halfway between them and there is a mathematical convention that such numbers get rounded up).

“显而易见”的答案是第一个例子应该四舍五入到 0.01(因为它更接近于 0.01 而不是 0.02),而另外两个应该四舍五入到 0.02(因为 0.0150000000000000001 更接近于 0.02 而不是 0.001 的一半,因为它正好介于 0.01 和它们并且有一个数学约定,这些数字会被四舍五入)。

The catch, which you may have guessed, is that roundTo2DPcannot possiblybe implemented to give those obvious answers, because all three numbers passed to it are the same number. IEEE 754 binary floating point numbers (the kind used by JavaScript) can't exactly represent most non-integer numbers, and so all three numeric literals above get rounded to a nearby valid floating point number. This number, as it happens, is exactly

您可能已经猜到的问题是,roundTo2DP不可能实现给出那些明显的答案,因为传递给它的所有三个数字都是相同的数字。IEEE 754 二进制浮点数(JavaScript 使用的那种)不能准确表示大多数非整数,因此上述所有三个数字文字都会四舍五入为附近的有效浮点数。这个数字,因为它发生,是正好

0.01499999999999999944488848768742172978818416595458984375

0.01499999999999999444888848768742172978818416595458984375

which is closer to 0.01 than to 0.02.

比 0.02 更接近 0.01。

You can see that all three numbers are the same at your browser console, Node shell, or other JavaScript interpreter. Just compare them:

您可以在浏览器控制台、Node shell 或其他 JavaScript 解释器中看到所有三个数字都相同。只需比较它们:

> 0.014999999999999999 === 0.0150000000000000001
true

So when I write m = 0.0150000000000000001, the exact value of mthat I end up with is closer to 0.01than it is to 0.02. And yet, if I convert mto a String...

所以当我写的时候,我最终m = 0.0150000000000000001得到的确切值m0.01比它更接近0.02。然而,如果我转换m为字符串......

> var m = 0.0150000000000000001;
> console.log(String(m));
0.015
> var m = 0.014999999999999999;
> console.log(String(m));
0.015

... I get 0.015, which should round to 0.02, and which is noticeably notthe 56-decimal-place number I earlier said that all of these numbers were exactly equal to. So what dark magic is this?

...我得到 0.015,它应该四舍五入到 0.02,这显然不是我之前所说的所有这些数字完全相等的 56 位小数位数。那么这是什么黑魔法呢?

The answer can be found in the ECMAScript specification, in section 7.1.12.1: ToString applied to the Number type. Here the rules for converting some Number mto a String are laid down. The key part is point 5, in which an integer sis generated whose digits will be used in the String representation of m:

答案可以在 ECMAScript 规范的第7.1.12.1节中找到:应用于 Number 类型的 ToString。这里规定了将某些 Number m转换为 String的规则。关键部分是第 5 点,其中生成了一个整数s,其数字将用于m的字符串表示:

let n, k, and sbe integers such that k≥ 1, 10k-1s< 10k, the Number value for s× 10n-kis m, and kis as small as possible. Note that k is the number of digits in the decimal representation of s, that sis not divisible by 10, and that the least significant digit of sis not necessarily uniquely determined by these criteria.

nks是整数,使得k≥ 1, 10 k-1s< 10 ks× 10 n- k 的数值是m,并且k尽可能小。请注意, k 是s的十进制表示中的位数,s不能被 10 整除,并且s的最低有效位不一定由这些标准唯一确定。

The key part here is the requirement that "kis as small as possible". What that requirement amounts to is a requirement that, given a Number m, the value of String(m)must have the least possible number of digitswhile still satisfying the requirement that Number(String(m)) === m. Since we already know that 0.015 === 0.0150000000000000001, it's now clear why String(0.0150000000000000001) === '0.015'must be true.

这里的关键部分是“ k尽可能小”的要求。该要求相当于要求,给定一个 Number m, 的值String(m)必须具有尽可能少的位数,同时仍满足 的要求Number(String(m)) === m。既然我们已经知道了0.015 === 0.0150000000000000001,现在很清楚为什么String(0.0150000000000000001) === '0.015'一定是真的。

Of course, none of this discussion has directly answered what roundTo2DP(m)shouldreturn. If m's exact value is 0.01499999999999999944488848768742172978818416595458984375, but its String representation is '0.015', then what is the correctanswer - mathematically, practically, philosophically, or whatever - when we round it to two decimal places?

当然,这些讨论都没有直接回答roundTo2DP(m)应该返回什么。如果m的确切值是 0.01499999999999999944488848768742172978818416595458984375,但它的字符串表示是 '0.015',那么正确的答案是什么- 数学上,实际上,我们在哲学上四舍五入到两位小数?

There is no single correct answer to this. It depends upon your use case. You probably want to respect the String representation and round upwards when:

对此没有唯一的正确答案。这取决于您的用例。在以下情况下,您可能希望尊重 String 表示并向上舍入:

  • The value being represented is inherently discrete, e.g. an amount of currency in a 3-decimal-place currency like dinars. In this case, the truevalue of a Number like 0.015 is0.015, and the 0.0149999999... representation that it gets in binary floating point is a rounding error. (Of course, many will argue, reasonably, that you should use a decimal library for handling such values and never represent them as binary floating point Numbers in the first place.)
  • The value was typed by a user. In this case, again, the exact decimal number entered is more 'true' than the nearest binary floating point representation.
  • 所表示的值本质上是离散的,例如以第纳尔等 3 位小数位货币表示的货币量。在这种情况下,像 0.015 这样的数字的真实0.015,而它以二进制浮点数表示的 0.0149999999... 表示是舍入误差。(当然,许多人会合理地争辩说,您应该使用十进制库来处理这些值,并且永远不要将它们表示为二进制浮点数。)
  • 该值是由用户键入的。在这种情况下,输入的精确十进制数比最接近的二进制浮点表示更“真实”。

On the other hand, you probably want to respect the binary floating point value and round downwards when your value is from an inherently continuous scale - for instance, if it's a reading from a sensor.

另一方面,当您的值来自固有的连续刻度时,您可能希望尊重二进制浮点值并向下舍入 - 例如,如果它是来自传感器的读数。

These two approaches require different code. To respect the String representation of the Number, we can (with quite a bit of reasonably subtle code) implement our own rounding that acts directly on the String representation, digit by digit, using the same algorithm you would've used in school when you were taught how to round numbers. Below is an example which respects the OP's requirement of representing the number to 2 decimal places "only when necessary" by stripping trailing zeroes after the decimal point; you may, of course, need to tweak it to your precise needs.

这两种方法需要不同的代码。为了尊重数字的字符串表示,我们可以(用相当多的相当微妙的代码)实现我们自己的舍入,直接作用于字符串表示,一个数字一个数字,使用与您在学校时使用的相同算法被教导如何舍入数字。下面是一个示例,它遵守 OP 的要求,即“仅在必要时”通过去除小数点后的尾随零来将数字表示为 2 位小数;当然,您可能需要根据您的具体需求对其进行调整。

/**
 * Converts num to a decimal string (if it isn't one already) and then rounds it
 * to at most dp decimal places.
 *
 * For explanation of why you'd want to perform rounding operations on a String
 * rather than a Number, see http://stackoverflow.com/a/38676273/1709587
 *
 * @param {(number|string)} num
 * @param {number} dp
 * @return {string}
 */
function roundStringNumberWithoutTrailingZeroes (num, dp) {
    if (arguments.length != 2) throw new Error("2 arguments required");

    num = String(num);
    if (num.indexOf('e+') != -1) {
        // Can't round numbers this large because their string representation
        // contains an exponent, like 9.99e+37
        throw new Error("num too large");
    }
    if (num.indexOf('.') == -1) {
        // Nothing to do
        return num;
    }

    var parts = num.split('.'),
        beforePoint = parts[0],
        afterPoint = parts[1],
        shouldRoundUp = afterPoint[dp] >= 5,
        finalNumber;

    afterPoint = afterPoint.slice(0, dp);
    if (!shouldRoundUp) {
        finalNumber = beforePoint + '.' + afterPoint;
    } else if (/^9+$/.test(afterPoint)) {
        // If we need to round up a number like 1.9999, increment the integer
        // before the decimal point and discard the fractional part.
        finalNumber = Number(beforePoint)+1;
    } else {
        // Starting from the last digit, increment digits until we find one
        // that is not 9, then stop
        var i = dp-1;
        while (true) {
            if (afterPoint[i] == '9') {
                afterPoint = afterPoint.substr(0, i) +
                             '0' +
                             afterPoint.substr(i+1);
                i--;
            } else {
                afterPoint = afterPoint.substr(0, i) +
                             (Number(afterPoint[i]) + 1) +
                             afterPoint.substr(i+1);
                break;
            }
        }

        finalNumber = beforePoint + '.' + afterPoint;
    }

    // Remove trailing zeroes from fractional part before returning
    return finalNumber.replace(/0+$/, '')
}

Example usage:

用法示例:

> roundStringNumberWithoutTrailingZeroes(1.6, 2)
'1.6'
> roundStringNumberWithoutTrailingZeroes(10000, 2)
'10000'
> roundStringNumberWithoutTrailingZeroes(0.015, 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes('0.015000', 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes(1, 1)
'1'
> roundStringNumberWithoutTrailingZeroes('0.015', 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes(0.01499999999999999944488848768742172978818416595458984375, 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes('0.01499999999999999944488848768742172978818416595458984375', 2)
'0.01'

The function above is probablywhat you want to use to avoid users ever witnessing numbers that they have entered being rounded wrongly.

上面的函数可能是您想要用来避免用户目睹他们输入的数字被四舍五入错误所用的功能。

(As an alternative, you could also try the round10library which provides a similarly-behaving function with a wildly different implementation.)

(作为替代方案,您也可以尝试使用round10库,该库提供了行为相似的函数,但实现方式却截然不同。)

But what if you have the second kind of Number - a value taken from a continuous scale, where there's no reason to think that approximate decimal representations with fewer decimal places are more accuratethan those with more? In that case, we don'twant to respect the String representation, because that representation (as explained in the spec) is already sort-of-rounded; we don't want to make the mistake of saying "0.014999999...375 rounds up to 0.015, which rounds up to 0.02, so 0.014999999...375 rounds up to 0.02".

但是,如果您有第二种 Number - 一个取自连续刻度的值,没有理由认为小数位数较少的近似小数表示比小数位数多的近似表示更准确呢?在这种情况下,我们希望尊重字符串表示,因为这表示(如规格说明)已经是全面的排序; 我们不想犯这样的错误:“0.014999999...375 四舍五入为 0.015,四舍五入为 0.02,所以 0.014999999...375 四舍五入为 0.02”。

Here we can simply use the built-in toFixedmethod. Note that by calling Number()on the String returned by toFixed, we get a Number whose String representation has no trailing zeroes (thanks to the way JavaScript computes the String representation of a Number, discussed earlier in this answer).

这里我们可以简单的使用内置的toFixed方法。请注意,通过调用Number()返回的字符串toFixed,我们得到一个数字,其字符串表示没有尾随零(感谢 JavaScript 计算数字的字符串表示的方式,在本答案前面讨论过)。

/**
 * Takes a float and rounds it to at most dp decimal places. For example
 *
 *     roundFloatNumberWithoutTrailingZeroes(1.2345, 3)
 *
 * returns 1.234
 *
 * Note that since this treats the value passed to it as a floating point
 * number, it will have counterintuitive results in some cases. For instance,
 * 
 *     roundFloatNumberWithoutTrailingZeroes(0.015, 2)
 *
 * gives 0.01 where 0.02 might be expected. For an explanation of why, see
 * http://stackoverflow.com/a/38676273/1709587. You may want to consider using the
 * roundStringNumberWithoutTrailingZeroes function there instead.
 *
 * @param {number} num
 * @param {number} dp
 * @return {number}
 */
function roundFloatNumberWithoutTrailingZeroes (num, dp) {
    var numToFixedDp = Number(num).toFixed(dp);
    return Number(numToFixedDp);
}

回答by AceCorban

回答by user

A precise rounding method. Source: Mozilla

一种精确的舍入方法。来源:Mozilla

(function(){

    /**
     * Decimal adjustment of a number.
     *
     * @param   {String}    type    The type of adjustment.
     * @param   {Number}    value   The number.
     * @param   {Integer}   exp     The exponent (the 10 logarithm of the adjustment base).
     * @returns {Number}            The adjusted value.
     */
    function decimalAdjust(type, value, exp) {
        // If the exp is undefined or zero...
        if (typeof exp === 'undefined' || +exp === 0) {
            return Math[type](value);
        }
        value = +value;
        exp = +exp;
        // If the value is not a number or the exp is not an integer...
        if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
            return NaN;
        }
        // Shift
        value = value.toString().split('e');
        value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
        // Shift back
        value = value.toString().split('e');
        return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }

    // Decimal round
    if (!Math.round10) {
        Math.round10 = function(value, exp) {
            return decimalAdjust('round', value, exp);
        };
    }
    // Decimal floor
    if (!Math.floor10) {
        Math.floor10 = function(value, exp) {
            return decimalAdjust('floor', value, exp);
        };
    }
    // Decimal ceil
    if (!Math.ceil10) {
        Math.ceil10 = function(value, exp) {
            return decimalAdjust('ceil', value, exp);
        };
    }
})();

Examples:

例子:

// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50

回答by machineaddict

None of the answers found here is correct. @stinkycheeseman asked to round up, you all rounded the number.

在这里找到的答案都不正确。@stinkycheeseman 要求四舍五入,你们都四舍五入了。

To round up, use this:

要四舍五入,请使用:

Math.ceil(num * 100)/100;