Atlas-Pio
Atlas-Pio

Reputation: 1153

How to round price in javascript? [Without Decimal]

I'm trying to round price like below :

850,005,500 round to 850,006,000. so my focus is on 4th / 5th number from right. More examples :

  1. 55,000 round to 60,000 OR 50,000
  2. 846,000 round to 850,000
  3. 1,504,000 round to 1,500,000
  4. 1,556,000 round to 1,560,000

So in above examples comas are not decimal, I'm just trying to split them for clear examples. How can i round this numbers up/down at 4th/5th position?

Thanks.

Upvotes: 1

Views: 124

Answers (2)

Ravi
Ravi

Reputation: 2281

You can use lodash module

var _ = require('lodash')
var number = 55000
_.round(number, -4)
_.round(number, -5)

To get floor value

_.floor(number, -4)

To get ceil value

_.ceil(number, -4)

Upvotes: 0

invisal
invisal

Reputation: 11181

You can achieve it by using divide and then multiply.

function roundPosition(n, pos) {
  const base = Math.pow(10, pos);
  return Math.round(n / base) * base;
}

console.log(roundPosition(154334, 4));  // round at position 4
console.log(roundPosition(154334, 5));  // round at position 5

Upvotes: 2

Related Questions