Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

round off decimal using javascript

I need to round off the decimal value to decimal places using javascript.

Ex,:

16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19

I have found some answers, but most of them do not round off 16.185 to 16.19..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);

If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)

And now as function:

function trueRound(value, digits){
    return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...