Skip to the code
cf.
+10 XP

#606 Group Digits in a Price

easy

A checkout page stores prices as whole numbers of cents to avoid rounding errors, and formats them only for display.

Write formatPrice(cents) that returns the amount in dollars as $1,234.56: a $, the whole dollars with a comma between every group of three digits counted from the right, a ., and exactly two digits of cents.

Negative amounts get a - before the $, as in -$0.05. Zero is $0.00.

Example 1

Input: cents = 123456
Output: "$1,234.56"

1234 dollars get one comma; 56 cents follow the dot.

Example 2

Input: cents = -5
Output: "-$0.05"

Five cents, negative, with the cents padded to two digits.

Constraints

  • -10^12 <= cents <= 10^12
  • cents is a whole number.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).