+ 1

# ❓❓❓How to round integer numbers so that the last digit is 0 (or 5)?

For example: 9 make 10 4569 make 4570 2 make 5 3222 make 3225 // always round to bigger (or 5 or 0) Maybe there is a special jd method? Thank you!

14 Answers

+ 9

1) Divide by 5
2) Math.ceiling
3) Multiply by 5

+ 3

Look up math ceiling for JavaScript.
Or...
https://www.sololearn.com/discuss/2469366/?ref=app
https://www.sololearn.com/discuss/2048566/?ref=app
https://www.sololearn.com/discuss/576946/?ref=app

+ 3

Jay Matthews , PR PRGR
you can write a simple function for this using if else or ternary expressions.
https://code.sololearn.com/WewelKPGp4RL/?ref=app

+ 3

let round = (n) => n+ (n%10 > 5 ? 10 : 5) - n%10;
console.log(round(3227))
console.log(round(3223))
Post your try.. Why special method for simple task.. You can write your own way..

+ 2

Jayakrishna 🇮🇳
your method is better.😎😎
using > simplifies the ternary expression.

+ 2

Jayakrishna 🇮🇳 yes, thank you! I know this, but I have a task to use exactly the method

+ 2

Bob_Li may be. But am not focused Jay Matthews sir method. It much simpler and straight forward. No need of any conditional check.
I thought 3 ways but it's steps🧐
PR PRGR special jd method? I thought you are looking inbuilt method. But now I understood you need procedure or algorithm in js way. 👍

+ 2

Jayakrishna 🇮🇳
I tried Jay Matthews method, but it does not round down. Math.ceil only rounds up.
let round = (n) => Math.ceil(n/5)*5
But yes, it solves the problem.
Maybe I misread the question. I was sure the original question also includes rounding down... my eyesight must be playing tricks on me.
PR PRGR, I also wondered if javascript had special round method for this, but I did not find any.

+ 2

Bob_Li
But the OP needs round up only.. ...
And in your solution, you need 0-5=> result 5 and 6-10=> result to 10. I think. Where round down is needed?

+ 2

Jayakrishna 🇮🇳 you are right.
I misread the question.
I thought round down was also involved.
Oh well, it's another method, if rounding down is needed.
I included Jay Matthews method in my code for reference if anyone is wondering how the two methods are different..

+ 1

Ausgrindtube thank you)

+ 1

Bob_Li thank you!!!!

+ 1

Jay Matthews answer is correct but may be sub-optimal. I tested Jay's ceiling method against this function:
function roundUpToNearest5or10(number) {
return number + (5 - (number % 5));
}
Using the modulo operator like this seems to take about 90% less time for the CPU to finish the calculations.
I'd be interested to see what other peoples' test results are.

0

Jay Matthews Thank you!