-1

so what i mean is:

1000 should become 10,00
10000 should become 100,00
100000 should become 1000,00

Can some help me out?

Grey Hack
  • 9
  • 1
  • 6
  • 1
    I think you want Intl.NumberFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat – Kinglish Dec 23 '21 at 19:26
  • What have you tried? It's just removing two last 00 and merging with `,` (basic string manipulation). E.g. `('' + number).replace(/(\d)(\d{2})$/, '$1,$2')` – Justinas Dec 23 '21 at 19:27
  • 1
    Does this answer your question? [How to format numbers as currency strings](https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings) – sukalogika Dec 23 '21 at 19:28
  • Are you working in Node.js? Client-side JS? For what country/locale/currency are you trying to format the value? Also it sounds like you are dealing with integer values in hundredths of a unit so as to avoid the problems of floating point, so $123.00 would be represented as the integer 12300, right? From a formatting point-of-view, that's a simple matter scaling the number appropriately. – Nicholas Carey Dec 23 '21 at 19:41
  • @Justinas, thanks you solved for me, i don't know how to make you're awnser the solution though – Grey Hack Dec 23 '21 at 19:43

3 Answers3

1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#using_options

var number = 1000;

// request a currency format
console.log(number.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));

Without methods and just formatting with commas

        function addComma(value) {
            return value.split('').map((v, i) => {
                if ( i === value.length - 2) {
                    return ',' + v
                }
                return v
            }).join('')
        }
        console.log(addComma('1000'))
        console.log(addComma('10000'))
        console.log(addComma('100000'))
Uzair Ashraf
  • 1,171
  • 8
  • 20
0

https://www.delftstack.com/howto/javascript/javascript-currency-format/

you can transform your string in number and then use toLocaleString()

here is an example from the webpage

const number = 2000;
number.toLocaleString('en-IN', {style: 'currency',currency: 'INR', minimumFractionDigits: 2})
console.log(number);
Gabo
  • 1
0

Another solution, just splitting the string into whole and cents:

function addComma(n)
{
    if (n.length == 0) {
       return '0,00';
    }

    if (n.length == 1) {
       return '0,0' + n;
    }

    if (n.length == 2) {
       return '0,' + n;
    }

    let whole = n.substring(0, n.length-2);
    let cents = n.substring(n.length-2);
    return whole + ',' + cents;
}
md2perpe
  • 3,372
  • 2
  • 18
  • 22