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!

7
  • 8
    number = number / 100 Commented Jul 5, 2017 at 3:16
  • 2
    I hate maths too Commented Jul 5, 2017 at 3:16
  • 3
    (number / 100).toFixed(2) Commented Jul 5, 2017 at 3:17
  • @JaromandaX I had this before but it wasn't working Commented Jul 5, 2017 at 3:18
  • really? what was it doing instead? Commented Jul 5, 2017 at 3:19

3 Answers 3

3

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

dollars = number / 100
Sign up to request clarification or add additional context in comments.

Comments

2

var number = 102042;

console.log(number/100);

1 Comment

102040 would not print the 100ths place.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.