jQuery 格式化通用货币数据
jQuery formating universal currency data
我正在尝试清算多种货币(例如美国和欧盟)并进行汇总。我要做的是;
10.30 → 10
10.60 → 11
849.95 → 850
1,022.20 → 1022
1.022,20 → 1022
230,20 → 230
30,20 → 30
如果用点分隔我可以做到,但是逗号不起作用https://jsfiddle.net/pmhgx7ut/
您应该可以这样做:
prices = [
'£6,000.98',
'£6.000,98',
'£600.30',
'£600,30',
'£200',
];
prices.forEach(price => {
// Check for a dot or comma followed by 2 digits at the end of price
const cents_match = price.match(/[\,\.](\d{2})$/);
// Check if we got a match and round the calue, or set cents to 0
const cents = cents_match ? Math.round(cents_match[1] / 100) : 0;
// Get the price without cents, add the rounded cents value.
price = +(cents_match ? price.slice(0, price.length - 3) : price).replace(/\D/g, '') + cents;
// Output
console.log(price);
});
在您已经编写的内容的基础上,您可以尝试以下操作:
var price = "1.022,20";
// comma and dot case
if (price.indexOf(',') < price.indexOf('.')) {
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");
};
// comma case
if (price.includes(",")==true && price.includes(".")==false)
{var price = price.replace(",",".");}
else //dot and comma case
{
if (price.indexOf('.') < price.indexOf(',')) {
var price = price.replace(",",".");
var price = price.replace(".",",");
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");};
};
var price = Math.round(price);
alert(price);
我正在尝试清算多种货币(例如美国和欧盟)并进行汇总。我要做的是;
10.30 → 10
10.60 → 11
849.95 → 850
1,022.20 → 1022
1.022,20 → 1022
230,20 → 230
30,20 → 30
如果用点分隔我可以做到,但是逗号不起作用https://jsfiddle.net/pmhgx7ut/
您应该可以这样做:
prices = [
'£6,000.98',
'£6.000,98',
'£600.30',
'£600,30',
'£200',
];
prices.forEach(price => {
// Check for a dot or comma followed by 2 digits at the end of price
const cents_match = price.match(/[\,\.](\d{2})$/);
// Check if we got a match and round the calue, or set cents to 0
const cents = cents_match ? Math.round(cents_match[1] / 100) : 0;
// Get the price without cents, add the rounded cents value.
price = +(cents_match ? price.slice(0, price.length - 3) : price).replace(/\D/g, '') + cents;
// Output
console.log(price);
});
在您已经编写的内容的基础上,您可以尝试以下操作:
var price = "1.022,20";
// comma and dot case
if (price.indexOf(',') < price.indexOf('.')) {
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");
};
// comma case
if (price.includes(",")==true && price.includes(".")==false)
{var price = price.replace(",",".");}
else //dot and comma case
{
if (price.indexOf('.') < price.indexOf(',')) {
var price = price.replace(",",".");
var price = price.replace(".",",");
var price = price.replace(/[^0-9\.\,]/g, '');
var price = price.replace(",","");};
};
var price = Math.round(price);
alert(price);