Dollar Format
September 30, 2016
We have a simple task today, a function that formats a number in dollar format. A number like 1234567.8912 should be rounded to two positions after the decimal point, have commas inserted every three positions before the decimal point, and have a dollar sign prepended; thus, the function should format 1234567.8912 as $1,234,567.89.
Your task is to write a function that returns numbers in dollar format; if your language provides such a facility natively, you are not permitted to use it. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Hi
/* 1234567.8912 as $1,234,567.89 */
function f$(f) {
/** MATH **/
/* 100,033 -> 10003,3 */
f = f*100
/* 10003,3 -> 10003 */
f = Math.round(f)
/* 10003 -> 100,03 */
f = f / 100.0
/** SRING **/
/* 100,03 -> [1,0,0,’,’,0,3] */
var ent = f.toString().split(‘.’)[0]
var dec = f.toString().split(‘.’)[1]
dec = dec+’00’
dec = dec.substr(0,3)
ent = ent.split(”)
ent = ent.reverse().map(function(c,i) {
if(i % 3 == 0 && i != 0)
return c+’,’
return c
}).reverse().join(”)
return ‘$’+ent+’.’+dec
}
console.log(f$(1000.200))
Thanks
ES6:
to$ = n => “$”+n.toFixed(2).replace(/(\d)(?=(\d\d\d)+\.)/g,”$1,”);
Demo: http://codepen.io/xem/pen/amyrxd
ES6, shorter:
to$ = n => “$”+n.toFixed(2).replace(/.(?=(…)+\.)/g,”$&,”);
Python 3 solution without using round() or str.format():
In Ruby