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
1.2k views
in Technique[技术] by (71.8m points)

math - Javascript: Round up to the next multiple of 5

I need a utility function that takes in an integer value (ranging from 2 to 5 digits in length) that rounds up to the next multiple of 5 instead of the nearest multiple of 5. Here is what I got:

function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}

When I run round5(32), it gives me 30, where I want 35.
When I run round5(37), it gives me 35, where I want 40.

When I run round5(132), it gives me 130, where I want 135.
When I run round5(137), it gives me 135, where I want 140.

etc...

How do I do this?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This will do the work:

function round5(x)
{
    return Math.ceil(x/5)*5;
}

It's just a variation of the common rounding number to nearest multiple of x function Math.round(number/x)*x, but using .ceil instead of .round makes it always round up instead of down/up according to mathematical rules.


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

...