Question

I have a script that takes a big number and counts up. The script converts the number to a string so that it can be formatted with commas, but I also need to add a decimal place before the last two digits. I know that this line handles the commas:

if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;

Is there a similar line of code I can add that accomplishes adding a decimal point?

Was it helpful?

Solution

Yes, if you always want the decimal before the last two:

function numberIt(str) {
    //number before the decimal point
    num = str.substring(0,str.length-3);
    //number after the decimal point
    dec = str.substring(str.length-2,str.length-1)
    //connect both parts while comma-ing the first half
    output = commaFunc(num) + "." + dec;

    return output;
}

When commaFunc() is the function you described that adds commas.

EDIT

After much hard work, the full correct code:

http://jsfiddle.net/nayish/TT8BH/21/

OTHER TIPS

Are you sure want the decimal to be just before the last two digits? That way 1234 would become 12.34 and not 1234.00, I'm assuming you want the second one, in that case you should use JavaScript's built in method .toFixed()

Note I didn't write the format_number function, I took it from the website below and modified it a bit.

http://www.mredkj.com/javascript/nfbasic2.html

http://www.mredkj.com/javascript/nfbasic.html

// example 1
var num = 10;
var output = num.toFixed(2); // output = 10.00

// example 2, if you want commas aswell
function format_number(nStr)
{
    nStr = nStr.toFixed(2);
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var num = 1234;
var output = format_number(num); // output = 1,234.00
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top