Regex/Javascript函数将价格存储为基于美分的数字

Regex/Javascript function to store prices as cent-based numbers

本文关键字:于美 数字 存储 Javascript 函数 Regex      更新时间:2023-09-26

Regex是那些你认为你有一个不错的解决方案的领域之一,直到你一开始就没有考虑到的问题出现。

我正试图从一个字符串中获取价格,比如:

US$1234.56
$12
$12.34usd
$0.56
.56 dollars

并将其转换为:

123456
1200
1234
56
56

分别。这样,它们就可以作为Numbers存储在我的数据库中,用于索引目的,所以我将值存储为美分。

目前我正在用regex:做这件事

var justPrice = fullPrice.replace(/[^0-9]/g, "");

这是有效的,但不考虑领先的0,也不适用于使$12==1200(而不仅仅是12,它将是12美分)。

我假设在vanilla regex中没有办法实现这个逻辑,所以在这里使用一些javascript是可以的。实现上述结果的最佳方法是什么?

我的解决方案是从任何小数位数的字符串中获取值,然后将字符串转换为数字并乘以100。

var stringPrice = fullPrice.replace(/[^0-9'.]/g, "");
var justPrice = Number(stringPrice) * 100;

也许我在这里遗漏了一些东西,但我认为在这种情况下,使用RegEx可能不是最好的主意。你可以试试这样的东西:

var priceParts = fullPrice.split('.'), justPrice = 0;
if (priceParts.length > 1) {
    if (priceParts[0] !== '' && priceParts[1] !== '') {
        justPrice = priceParts[0].replace(/'D/, '') * 100
                    + priceParts[1].replace(/'D/, '');
    } else if (priceParts[0] !== '') {
        justPrice = priceParts[0].replace(/'D/, '') * 100;
    } else if (priceParts[1] !== '') {
        justPrice = priceParts[1].replace(/'D/, '');
    }
} else {
    justPrice = priceParts[0].replace(/'D/, '') * 100;
}