How to round down integer to all zeros behind first number

Viewed 39

For example, I need to round number 6588 => 6000 , 1285000 => 1000000

I can't find any Math.ceil , Math.floor methods that can achieve this.

4 Answers

You can divide by the highest power of ten, floor it, then multiply back by the highest power of ten. Some other answers are manipulating string, but IMO this is the simplest and easiest to read code. Like this:

function roundDown(num) {
    let powerOfTen = num.toString().length - 1;
    num /= (10**powerOfTen);
    return Math.floor(num) * (10**powerOfTen);
}

console.log(roundDown(6588))    // => 6000
console.log(roundDown(1285000)) // => 1000000

This is roughly the same procedure that Math.floor() uses, as described in this MDN article;

another variant is just work on string level, instead of numbers to avoid any floating point problems

 function roundToFirst(n) {
  return (''+n).split('').map((c, i) => i > 0 ? '0' : c).join('');
 }
 
 console.log(roundToFirst(6588)); // 6000
 console.log(roundToFirst(1285000)); // 1000000

You can convert your number to a string and simply append zeros to match the number's length.

const roundDown = (num) => {
  num = num.toString();
  return (num[0] + new Array(num.length).join('0'));
}

console.log(roundDown(6588))
console.log(roundDown(0))

A short and easy way is to take the first digit and padEnd the rest

const roundDown = num => {
  num = String(num)
  return +num[0].padEnd(num.length, "0")
}

console.log(roundDown(6588))
console.log(roundDown(1285000))

References

padEnd

Related