Reputation: 7
For some calculations, I need to get the closest number in tens, hundreds, thousands...etc of a given number. Examples:
1 becomes 10
3 becomes 10
15 becomes 20
36 becomes 40
105 becomes 110
1009 becomes 1010
... etc
Thanks in advance!
Upvotes: 0
Views: 135
Reputation: 391
Revansiddh answer is really nice, only to 'fullier' answer the question:
function roundOff(num, precision = 10){
return (precision - (num%precision)) + num
}
console.log("round off of 1009",roundOff(1049))
console.log("round off of 105",roundOff(1049, 100))
console.log("round off of 36",roundOff(1049, 1000))
Upvotes: 0
Reputation: 3072
Simple javascript add reminder to number. by using mod of unit digit
Use roundOff
function from below example pass digit it will return.
function roundOff(num){
return (10 - (num%10)) + num
}
console.log("round off of 1009",roundOff(1009))
console.log("round off of 105",roundOff(105))
console.log("round off of 36",roundOff(36))
Upvotes: 1
Reputation: 5912
You can do this.
let i = 105;
let result = (parseInt(i/10, 10)+1)*10;
console.log(result);
Upvotes: 1