+ 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!

28th Jan 2023, 12:51 AM
PR PRGR
PR PRGR - avatar
13 Respostas
+ 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
28th Jan 2023, 5:02 AM
Bob_Li
Bob_Li - avatar
+ 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..
28th Jan 2023, 11:34 AM
Jayakrishna 🇼🇳
+ 2
Jayakrishna 🇼🇳 your method is better.😎😎 using > simplifies the ternary expression.
28th Jan 2023, 12:13 PM
Bob_Li
Bob_Li - avatar
+ 2
Jayakrishna 🇼🇳 yes, thank you! I know this, but I have a task to use exactly the method
28th Jan 2023, 7:31 PM
PR PRGR
PR PRGR - avatar
+ 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. 👍
28th Jan 2023, 8:00 PM
Jayakrishna 🇼🇳
+ 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.
28th Jan 2023, 8:57 PM
Bob_Li
Bob_Li - avatar
+ 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?
28th Jan 2023, 9:11 PM
Jayakrishna 🇼🇳
+ 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..
28th Jan 2023, 9:14 PM
Bob_Li
Bob_Li - avatar
+ 1
Ausgrindtube thank you)
28th Jan 2023, 7:29 PM
PR PRGR
PR PRGR - avatar
+ 1
Bob_Li thank you!!!!
28th Jan 2023, 7:32 PM
PR PRGR
PR PRGR - avatar
+ 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.
29th Jan 2023, 11:38 PM
Sam
0
Jay Matthews Thank you!
28th Jan 2023, 7:29 PM
PR PRGR
PR PRGR - avatar