Marko
Marko

Reputation: 72232

Round money to nearest 10 dollars in Javascript

How can I round a decimal number in Javascript to the nearest 10? My math is pretty rubbish today, it could be the 2 hour sleep :/

Some sample cases

$2823.66  = $2820
$142.11 = $140
$9.49 = $10

I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.

Any help/pointers appreciated!

M

Upvotes: 26

Views: 22295

Answers (5)

yckart
yckart

Reputation: 33428

function round(number, multiplier) {
  multiplier = multiplier || 1;
  return Math.round(number / multiplier) * multiplier;
}

var num1 = 2823.66;
var num2 = 142.11;
var num3 = 9.49;

console.log(
  "%s\n%s\n%s", // just a formating thing
  round(num1, 10), // 2820
  round(num2, 10), // 140
  round(num3, 10)  // 10
);

Upvotes: 2

morgancodes
morgancodes

Reputation: 25265

10 * Math.round(val / 10)

Upvotes: 4

Sebastián Grignoli
Sebastián Grignoli

Reputation: 33452

Use this function:

function roundTen(number)
{
  return Math.round(number/10)*10;
}



alert(roundTen(2823.66));

Upvotes: 12

paxdiablo
paxdiablo

Reputation: 882078

To round a number to the nearest 10, first divide it by 10, then round it to the nearest 1, then multiply it by 10 again:

val = Math.round(val/10)*10;

This page has some details. They go the other way (e.g., rounding to the nearest 0.01) but the theory and practice are identical - multiply (or divide), round, then divide (or multiply).

Upvotes: 9

Toby
Toby

Reputation: 1660

Try

Math.round(val / 10) * 10;

Upvotes: 71

Related Questions