2

I'm given numbers in cents:

eg.

  102042
  982123
  121212

I want to convert them to dollars. I figured the easiest way to do this is to convert the digits into a string and add a decimal.

eg.

  1020.42
  9821.23
  1212.12

I'm currently doing this but it only rounds to 1 decimal. What would I need to do it make it round to 2 decimals?

var number = 102042
number.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]

UPDATE: I found out what my issue was. It wasn't the rounding but the fact that I combined a lodash filter to a division incorrectly. Thanks again!

lost9123193
  • 9,040
  • 22
  • 62
  • 100

3 Answers3

3

A cent is 1/100th of a dollar, so you can calculate the dollar amount by doing

dollars = number / 100
Matt
  • 698
  • 6
  • 19
2

var number = 102042;

console.log(number/100);
Dinesh undefined
  • 5,362
  • 2
  • 17
  • 39
2

The easiest way is to do it with the number itself, you can multiply by 0.01 or divide by 100 and you'll get that amount in dollars:

var numbers = [102042,982123,121212];

for(num of numbers) 
  console.log(num/100);
JV Lobo
  • 5,136
  • 8
  • 29
  • 50