Javascript: Format Number, Price, Amount
posted by sacah on javascript, programming, sacah,
After looking around at many different number formatting scripts, I figured surely the joy of regular expressions could do this is far fewer lines of code, so off I set and below is my creation. First is the two line function, below that I have put each statement on a new line for ease of explaining what/how it does its formatting.
Output
Simply converts number into a string.
Replaces anything that isn’t a digit (\d), a full stop (.) or a minus sign (-) with an empty string (‘’). This will get rid of dollar signs, already existing formatting like commas etc.
Detects the first 2 digits after the first full stop (.\d{2}) and captures this info. Then detects all characters after the first two digits till the end of the line [\W\w]+. All this gets replaced with the first match. eg 100.1234 (.\d{2}) matches .12 and [\W\w]+ matches 34. Then .1234 gets replaced with .12
Split the string into an Array.
Reverse the array.
Join the array back into a String.
Match groups of 3 digits (\d{3}), and replace them with the matches text followed by a comma $1,.
Split the string into an Array again.
Reverse the array again.
Join the array back to a string.
Matches 0 to 1 occurrences of a minus sign ([-]{0,1}) at the start of a line (^), followed by a comma. This gets replaced by the first match, which is either an empty string or a minus sign. -,123 becomes -123.
Matches a single digit following a full stop (.\d) at the end of the line ($), and replaces this with the full stop and digit plus a 0. 1.1 becomes 1.10
Matches a full stop at the end of the line, and replaces it with .00