Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Necuima

Formatting A Currency Amount Which Is In A Double - Script 3.1

Recommended Posts

I was interested to format the loan amount when the result of the mortgage repayment calculation is displayed and I came across this code (which I modified a little). And thanks to the author whose name I don't know.

 

It takes a value in a double and returns a string formatted for currency with two decimal places.

 

Thought I'd post it for what it's worth.

#include <string>
std::string formatCurrency(double dv)

{

    const std::string radix = ".";

    const std::string thousands = ",";

    const std::string unit = "$";

    unsigned long v = (unsigned long) ((dv * 100.0) + .5);

    std::string fmt,digit;

    int i = -2; // number of decimal places - DO NOT CHANGE!!

    do {

        if(i == 0) {

            fmt = radix + fmt;

        }

        if((i > 0) && (!(i % 3))) {

            fmt = thousands + fmt;

        }

        digit = (v % 10) + '0';

        fmt = digit + fmt;

        v /= 10;

        i++;

    }

    while((v) || (i < 1));

    std::string rv;

    rv = unit + fmt;

    return rv;

}

Cheers from Oz.

Share this post


Link to post
Share on other sites

After playing around with this, it only works for numbers that fit into the numeric data types used.  If you put in a too-large number, the result is garbage!

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...