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.

Advertisement

Pages: 1 2

6 Responses to “Dollar Format”

  1. matthew said
    (display (dollar 1234567.9999)) (newline)
    $1,234,567.100
    
  2. tchaardge said

    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

  3. xem said

    ES6:

    to$ = n => “$”+n.toFixed(2).replace(/(\d)(?=(\d\d\d)+\.)/g,”$1,”);

    Demo: http://codepen.io/xem/pen/amyrxd

  4. maximeeuziere said

    ES6, shorter:

    to$ = n => “$”+n.toFixed(2).replace(/.(?=(…)+\.)/g,”$&,”);

  5. Alex B. said

    Python 3 solution without using round() or str.format():

    def dollars(n):
        '''Format a number as a dollar amount string'''
        n = int(n*100)
        s = str(n)
        i, d = s[:-2], s[-2:]
        l = [i[(c-3 if c >= 3 else 0):c] for c in range(len(i),0,-3)]
        o = '.'.join((','.join(reversed(l)),d))
        return ''.join(('$', o))
    
  6. V said

    In Ruby

    
      def format(amount)
        decimal, fraction = amount.round(2).to_s.split('.')
        decimal_part = decimal.
          chars.
          reverse.
          each_slice(3).
          map { |xs| xs.reverse.join }.
          reverse.
          join(",")
    
        "$" + decimal_part + "." + fraction.ljust(2, "0")
      end
      
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: