Dollar Format
September 30, 2016
This isn’t hard, just tedious; exactly how you do it depends on the features your language provides:
(define (dollar x) (define (commas n) (let ((xs (reverse (map number->string (digits n))))) (let loop ((xs (drop 3 xs)) (zs (reverse (take 3 xs)))) (if (null? xs) (apply string-append zs) (loop (drop 3 xs) (append (reverse (take 3 xs)) (list ",") zs)))))) (define (zero n) (if (zero? n) "00" (if (< n 10) (string-append "0" (number->string n)) (number->string n)))) (let* ((dollars (inexact->exact (floor x))) (cents (inexact->exact (round (* 100 (- x dollars)))))) (string-append "$" (commas dollars) "." (zero cents)))) > (dollar 1234567.8912) "$1,234,567.89"
You can run the program at http://ideone.com/978aEz.
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