0

I'm confused about how to add two digits in this function I want the result to be as in the following example : 1.000.000,00

my code :

function FormatCurrency2(objNum) {
  if (objNum.value.substring(0, 1) == "0") {
    objNum.value = objNum.value.replace(/^0+/g, '');
  }

  var num = objNum.value;
  var ent, dec;
  if (num != '' && num != objNum.oldvalue) {
    num = HapusTitik(num);
    if (isNaN(num)) {

      // objNum.value = (objNum.oldvalue)?objNum.oldvalue:'';
    } else {
      var ev = (navigator.appName.indexOf('Netscape') != 1) ? Event : event;
      if (ev.keyCode == 190) {
        // alert(num.split('.')[1]);
        objNum.value = TambahTitik(num.split('.')[0]) + '.' + num.split('.')[1];
      } else {
        objNum.value = TambahTitik(num.split('.')[0]);
      }
      objNum.oldvalue = objNum.value;
    }
  }
}
Kaiido
  • 123,334
  • 13
  • 219
  • 285

1 Answers1

0

Sounds like you want Number.prototype.toLocaleString, with the locale set to de-DE maybe, and the minimumFractionDigits option set to 2:

const num = 1000000;
const str = num.toLocaleString('de-DE', {minimumFractionDigits:2})
console.log(str);

And if you wish to fix it to two digits, then you'd have to also set the maximumFractionDigits:

const num = 1000000 + Math.PI;
const str = num.toLocaleString('de-DE', {
  minimumFractionDigits:2,
  maximumFractionDigits:2
})
console.log(str);
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I using keyup function but can't work. function FormatCurrency3(num) { var digit = num.value; const str = digit.toLocaleString('de-DE', {minimumFractionDigits:2}); console.log(str); return str; } – ahmad ainul yaqin r Apr 22 '19 at 08:11
  • `HTMLInputElement.value` is always a string, the `toLocaleString` method I referred to is the `Number.prototype`'s one. You need to cast `digit` to a number e.g `digit = Number(num.value);` or if `num` is an input of `type` `"number"`, then you can use its `.valueAsNumber` property. – Kaiido Apr 22 '19 at 08:17
  • thanks.. now work. but the value form input can't change value as '1.000.000,00'. I wan't to if type in form automatic change on form. function FormatCurrency3(num) { const digit = Number(num.value); const str = digit.toLocaleString('de-DE', {minimumFractionDigits:2}); return str; } HTML – ahmad ainul yaqin r Apr 22 '19 at 08:47
  • Well yes, `Number("1.000.000,00")` will return `NaN`. You'd have to parse it manually. – Kaiido Apr 22 '19 at 08:55
  • how to automatic type change on form? not change on console.log – ahmad ainul yaqin r Apr 22 '19 at 09:19