Javascript toLocaleString onKeyUp事件

时间:2018-04-23 04:23:17

标签: javascript converter currency onkeyup

我需要一些帮助来解决这个问题,我正在尝试在输入时从value标签打印出<input>,并且应该打印出千位分隔符,但它会像我输入的那样返回数字,更准确地说它不起作用。我该怎么解决这个问题??

function cDes(e) {
  var k = e.currentTarget;
  var prc = k.value; //example value: 123456789
  var prc_f = prc.toLocaleString('de-DE');
  var oDiv = document.getElementById('cOut');
  if (e.keyCode == 13) {
    if (prc.length < 1) {
      oDiv.innerHTML = 'FREE';
    } else {
      oDiv.innerHTML = prc_f; //expected output value: 123.456.789
    }
  } else {
    oDiv.innerHTML = '...';
  }
}
<input type='number' id='price' onKeyUp='cDes(event)'>

<div id='cOut'></div>

2 个答案:

答案 0 :(得分:3)

在使用Number.toLocaleString()之前将输入字符串转换为数字:

var prc_f = Number(prc).toLocaleString('de-DE');

示例:

&#13;
&#13;
// get a reference to the element once
var oDiv = document.getElementById('cOut');

function cDes(e) {
  var prc = e.target.value; //example value: 123456789
  if (e.keyCode == 13) {
    if (prc.length < 1) {
      oDiv.innerHTML = 'FREE';
    } else {
      // you only need to convert the input when you display it
      oDiv.innerHTML = Number(prc).toLocaleString('de-DE'); //expected output value: 123.456.789
    }
  } else {
    oDiv.innerHTML = '...';
  }
}
&#13;
<input type='number' id='price' onKeyUp='cDes(event)'>

<div id='cOut'></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这个答案可能与您的期望略有不同,但如果客观是显示价格和符号,您可以使用Intl.NumberFormat

function cDes(e) {
  var k = e.currentTarget;
  var prc = k.value; //example value: 123456789
  var prc_f = nf.format(prc);
  var oDiv = document.getElementById('cOut');
  if (e.keyCode == 13) {
    if (prc.length < 1) {
      oDiv.innerHTML = 'FREE';
    } else {
      oDiv.innerHTML = prc_f; //expected output value: 123.456.789
    }
  } else {
    oDiv.innerHTML = '...';
  }
}
var nf = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
  minimumFractionDigits: 0,
  maximumFractionDigits: 2
});
<input type='number' id='price' onKeyUp='cDes(event)'>

<div id='cOut'></div>