How to round down integers in JavaScript?

Hey everyone! I’m scratching my head over this one. I need to round down whole numbers in JavaScript, but I’m not sure how to do it. I’ve tried using Math.floor(), but it’s not giving me the results I want.

Here’s what I’m aiming for:

function roundDown(num) {
  // Enter your code here?
}

console.log(roundDown(29));  // Should output 20
console.log(roundDown(4456));  // Should output 4450
console.log(roundDown(111));   // Should output 110
console.log(roundDown(9));     // Should output 9 (should not become 0)

I’m looking to round down to the nearest ten, except in cases where the number is a single digit. I’ve sifted through various forums and documentation, but nothing has really worked out the way I hoped. Any ideas would be greatly appreciated!

hey mate, I think i got a solution 4 ya. try this:

roundDown = n => n < 10 ? n : ~~(n/10)*10

it uses the double tilde (~~) trick to floor the number. its like a shortcut for Math.floor(). pretty neat, huh? lemmie know if it works for ya!

I’ve worked with rounding in JavaScript quite a bit, and your case is interesting. Here’s an approach that should do the trick:

function roundDown(num) {
return num < 10 ? num : Math.floor(num / 10) * 10;
}

This uses a ternary operator to handle single-digit numbers separately. For larger numbers, it divides by 10, floors the result, then multiplies by 10 again. This effectively rounds down to the nearest ten while preserving single-digit numbers.

It’s a concise solution that meets all your requirements. I’ve used this method in production code, and it’s proven to be both efficient and reliable. Give it a try and see if it works for your specific use case.

I’ve encountered a similar problem in my projects before. The key is to use a combination of Math.floor() and some basic arithmetic. Here’s a solution that should work for you:

function roundDown(num) {
if (num < 10) return num;
return Math.floor(num / 10) * 10;
}

This function first checks if the number is less than 10. If it is, it returns the number as-is. For numbers 10 and above, it divides by 10, rounds down using Math.floor(), then multiplies by 10 again.

The division and multiplication by 10 effectively shift the decimal point, allowing us to round down to the nearest ten. This approach is efficient and works for any positive integer.

Hope this helps solve your problem!