Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Using toFixed(2) and math round to get correct rounding

I would like to find a function that will return this kind of formatted values :

1.5555 => 1.55
1.5556 => 1.56
1.5554 => 1.55
1.5651 => 1.56

toFixed() and math round return this value :

1.5651.fixedTo(2) => 1.57

This will be usefull for money rounding.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

How about this?

function wacky_round(number, places) {
    var multiplier = Math.pow(10, places+2); // get two extra digits
    var fixed = Math.floor(number*multiplier); // convert to integer
    fixed += 44; // round down on anything less than x.xxx56
    fixed = Math.floor(fixed/100); // chop off last 2 digits
    return fixed/Math.pow(10, places);
}

1.5554 => 1.55

1.5555 => 1.55

1.5556 => 1.56

1.5651 => 1.56

So, that works, but I think you'll find that it's not a generally-accepted way to round. http://en.wikipedia.org/wiki/Rounding#Tie-breaking


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...