Skip to content

Inconsistent rounding results using multiply-and-divide method #3877

@0xkrnn

Description

@0xkrnn

Multiply-and-divide.

For example, to round the number to the 2nd digit after the decimal, we can multiply the number by 100, call the rounding function and then divide it back.

let num = 1.23456;
alert( Math.round(num * 100) / 100 ); // 1.23456 -> 123.456 -> 123 -> 1.23

In the documentation you mentioned two ways to reduce the the number of decimal places. However, the first method can give inconsistent results because of the Math.round() method.

for example if the number is 1.23567
the result will be 1.24 instead of 1.23

let num = 1.23567;
alert( Math.round(num * 100) / 100 ); // 1.23456 -> 123.456 -> 124 -> 1.24

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions