How do I round a number in JavaScript?

2020-01-24 11:49发布

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2

etc.

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?

8条回答
\"骚年 ilove
2楼-- · 2020-01-24 12:17

If you need to round to a certain number of digits use the following function

function roundNumber(number, digits) {
            var multiple = Math.pow(10, digits);
            var rndedNum = Math.round(number * multiple) / multiple;
            return rndedNum;
        }
查看更多
叛逆
3楼-- · 2020-01-24 12:18

You can also use toFixed(x) or toPrecision(x) where x is the number of digits.

Both these methods are supported in all major browsers

查看更多
登录 后发表回答