tariklp
tariklp

Reputation: 7

React: How can I get the closest number in tens, hundreds, thousands... of a given number?

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

Answers (3)

Stephan Hovius
Stephan Hovius

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

Revansiddh
Revansiddh

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

Amruth
Amruth

Reputation: 5912

You can do this.

let i = 105;
let result = (parseInt(i/10, 10)+1)*10;  
console.log(result); 

Upvotes: 1

Related Questions