显示数字中的货币

时间:2018-02-28 09:54:11

标签: javascript jquery numbers format

如何在实时输入/输入时将数字(整数)更改为货币格式?

前:

45678 => 456.78

234567 => 2345.67  or 2,345.67 or 2 345.67

(取决于使用的掩码格式)

在人们开始将此问题标记为现有问题之前,我已经看到了格式化数字的现有代码,但这些示例不会将最后两个数字作为小数处理。而是将字符串45678格式化为45 678.00或45,678.00而不是456.78。

像convert这样的东西:

######## into ### ###.##

5 个答案:

答案 0 :(得分:2)

您可以迭代掩码并重新组合结果字符串。

它从两个值创建两个数组(spread syntax ...),用于数组中的单个数字或掩码字符。

然后它从右侧迭代掩码字符

(m === '#' ? v.pop() || '' : v.length ? m : '') + s

如果找到#,则使用数值构建一个新字符串

 m === '#' ? v.pop() || ''

或通过检查值的长度来获取掩码的值

                             v.length ? m : ''

以防止添加空格或不需要的字符。

function convert(i, mask) {
    var v = [...i.toString()];
    return [...mask].reduceRight((s, m) => (m === '#' ? v.pop() || '' : v.length ? m : '') + s, '');
}

console.log(convert(45678, '### ###.##')); // 456.78
console.log(convert(234567, '### ###.##')); // 2345.67
console.log(convert(234567, '###,###.##')); // 2,345.67
console.log(convert(234567, '### ###.##')); // 2 345.67 

答案 1 :(得分:1)

在键入输入时添加事件处理程序以格式化该输入的值。

$('#myTextbox').keyup(function(){
    $(this).val(($(this).val() /100).toFixed(2);
});

答案 2 :(得分:1)

(number).toFixed()函数将数字转换为字符串。为避免这种情况,请尝试:

var x4 = 999546765687;
x4 = x4/100;
x4.toFixed(2);
Number(x4)

答案 3 :(得分:0)

  

toLocaleString()方法返回一个字符串,其中包含此编号的语言敏感表示。

var currency = 234567/100;
var currencyString = currency.toLocaleString('en-US')
console.log(currencyString);

答案 4 :(得分:0)

对于角度

https://angular.io/api/common/CurrencyPipe

尝试使用
   @零件({       选择器:'currency-pipe',       模板:`                  

答:{{a |货币}}

    <!--output 'CA$0.26'-->
    <p>A: {{a | currency:'CAD'}}</p>

    <!--output 'CAD0.26'-->
    <p>A: {{a | currency:'CAD':'code'}}</p>

    <!--output 'CA$0,001.35'-->
    <p>B: {{b | currency:'CAD':'symbol':'4.2-2'}}</p>

    <!--output '$0,001.35'-->
    <p>B: {{b | currency:'CAD':'symbol-narrow':'4.2-2'}}</p>

    <!--output '0 001,35 CA$'-->
    <p>B: {{b | currency:'CAD':'symbol':'4.2-2':'fr'}}</p>
  </div>`
})
export class CurrencyPipeComponent {
  a: number = 0.259;
  b: number = 1.3495;
}