[英]Format string as currency REGEX
I'm currently trying to transform some data before displaying on NetSuite server side with suitescript 1.我目前正在尝试在使用套件脚本 1 在 NetSuite 服务器端显示之前转换一些数据。
Unfortunately, can't use toLocaleString .不幸的是,不能使用toLocaleString 。
Data![]() |
Output ![]() |
Expected![]() |
---|---|---|
1000 ![]() |
1000USD ![]() |
1,000.00 USD ![]() |
1 ![]() |
1EUR ![]() |
1.00 EUR ![]() |
2000000.1 ![]() |
2000000.1GBD ![]() |
2,000,000.10 GBD ![]() |
Any idea how I can accomplish that?知道我怎么能做到这一点吗? mostly looking to do it with a simple function like this one
主要是想用一个简单的 function 来做这个
fuction formatThis(str){
return String(str).replace(/(.)(?=(\d{3})+$)/g, '$1,');
}
If your version of NetSuite is 2.0, you may only have access to ECMA Script 5.1如果您的 NetSuite 版本是 2.0,您可能只能访问 ECMA Script 5.1
Here is a function that would do the formatting without using ECMAScript 2015 features.这是一个 function 可以在不使用 ECMAScript 2015 功能的情况下进行格式化。 It takes a second argument for the currency.
货币需要第二个参数。 I don't see that anywhere in your examples on the input side:
我在输入端的示例中看不到任何地方:
function format(str, currency) { return (str + ".00").replace(/(\.\d)\.00/, "$10").replace(/\.+(\d{0,2}).*/, ".$1 " + currency).replace(/\d(?=(\d{3})+\b)/g, "$&,"); } // Examples: console.log(format("1000", "USD")); console.log(format("1", "EUR")); console.log(format("2000000.1", "GBD"));
You can extract the leading number, and format the currency using a bunch of regexes:您可以提取前导数字,并使用一堆正则表达式格式化货币:
function formatCurrency(str) { return str.replace(/^[0-9\.]+/, function(m) { // extract the leading number return parseInt(Number(m) * 100, 10) // convert the number to cents.toString() // convert back to string.replace(/(..)$/, '.$1') // add dot, eg restore currency from cents.replace(/(.{12})$/, ',$1') // add comma to billion.replace(/(.{9})$/, ',$1') // add comma to million.replace(/(.{6})$/, ',$1') // add comma to thousand + ' '; }); } [ '1000USD', '1EUR', '2000000.1GBD' ].forEach(str => { console.log(str + ' => ' + formatCurrency(str)); });
Output: Output:
1000USD => 1,000.00 USD
1EUR => 1.00 EUR
2000000.1GBD => 2,000,000.10 GBD
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.