简体   繁体   English

React / Javascript 中的货币格式

[英]Currency formatting in React / Javascript

Good afternoon folks!各位下午好!

I'm using React NumberFormat for currency formatting, it works well, but I couldn't reproduce with it the behavior I want for my page.我正在使用 React NumberFormat 进行货币格式化,它运行良好,但我无法用它重现我想要的页面行为。

I would like the user to type in the 1010 input, and the input automatically corrects it to $ 10.10.我希望用户输入 1010 输入,输入自动将其更正为 $10.10。

However, all the methods I found, when the user types 1010, he corrects it for $ 1010.00.但是,我找到的所有方法,当用户键入 1010 时,他将其更正为 $1010.00。

How do I get to this behavior in real time in the input?我如何在输入中实时获得这种行为? As soon as the user types, it is already formatting.只要用户输入,它就已经在格式化。

Appreciate!欣赏!

I need a regular expression or code, where:我需要一个正则表达式或代码,其中:

I type - return code我输入 - 返回码

1010 ===> 10.10
1000 ====> 10.00
1050 =====> 10.50
100050 ====> 1,000.50

You can try making a "format" function like below:您可以尝试制作一个“格式”功能,如下所示:

function formatCurrency(currencyString) {   
    let firstHalf = currencyString.substring(0, currencyString.length - 2);
    let secondHalf = currencyString.substring(currencyString.length - 2, currencyString.length);
    return parseFloat(`${firstHalf}.${secondHalf}`).toLocaleString('en-EN', {style: 'currency', currency: 'USD'});
}

// example use case: 
let cur = formatCurrency('1010'); // returns: '$10.10'
cur = formatCurrency('101010') // returns: '$1,010.10'

This way you are always getting the last two characters on the right side of the decimal, as you're trying to do, and using localization to properly format the number.通过这种方式,您总是可以得到小数点右侧的最后两个字符,正如您所尝试的那样,并使用本地化来正确设置数字格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM