Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

Format a number to currency

I found this code on stackoverflow but I don't really understand it, it only does what I want when the digit is 5 numbers or below, the currency should be formatted like this:

5000 > 5,000.00 
10000 > 10,000.00 
150000 > 150,000.00 
1000000 > 1,000,000.00

The code works for the first 2 but not the last ones

formatMoney(number) {
    var decPlaces = 2;
    var decSep = ".";
    var thouSep = ",";
    var sign = number < 0 ? "-" : "";
    var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
    var j = (j = i.length) > 3 ? j % 3 : 0;

    return sign +
        (j ? i.substr(0, j) + thouSep : "") +
        i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "" + thouSep) +
        (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
},

How can I get it to work as expected?

0 likes
8 replies
eggplantSword's avatar

@michaloravec Using the correct locale doesn't really do it for me the way I want, realistically I could drop the .00 at the end and just have 5,000. This returns CRC 10,000.00 Is there a way I can change the CRC for the actual symbol?

return new Intl.NumberFormat("en-US", { style: 'currency', currency: 'CRC' }).format(number)
MichalOravec's avatar

@msslgomez Instead of en-US you have to use es-CR then you get the correct symbol

return new Intl.NumberFormat('es-CR', { style: 'currency', currency: 'CRC' }).format(number);
eggplantSword's avatar

@michaloravec I tried that but it returns ₡10 000,00 the space and comma are incorrect, only accountants use this format all stores that show a price for something do it like this ₡10,000.00 or just ₡10,000

MichalOravec's avatar

@msslgomez So just

formatMoney(number) {
    return '₡' + (number).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
Snapey's avatar

or, if your value is in number

'₡' + number.toLocaleString('en',{style:'decimal'})

Please or to participate in this conversation.