vue3 | currency.js插件 | 浮点型数据计算 | 精度处理

1,042 阅读2分钟

vue3在处理浮点型数据时会出现精度丢失的问题,这时候就要用插件来完成数据处理

官网:currency.js.org/

image.png currency.js 的构建是为了通过灵活的 API 解决 javascript 中常见的浮点问题。

在使用货币时,小数只需精确到最小的美分值,同时避免在执行基本算术时出现常见的浮点错误。currency.js通过在后台使用整数来解决此问题,因此您不必担心小数精度

安装

With npm:

npm install --save currency.js

With yarn:

yarn add currency.js

使用

currency.js将处理一系列输入,包括numbersdecimalscurrencystrings或其他对象。

// Numbers 
currency(1); // => "1.00" 
currency(123); // => "123.00" 

// Decimals 
currency(1.00); // => "1.00" 
currency(1.23); // => "1.23" 

// Strings 
currency("1.23"); // => "1.23" 
currency("$12.30"); // => "12.30" 
currency("£1,234,567.89"); // => "1,234,567.89" 

// Currency 
let c1 = currency(1.23); 
let c2 = currency(4.56); 
currency(7.89).add(c1).add(c2); // => "13.68"

由于currency.js在内部将值作为整数处理,因此在遇到精度错误之前可以存储的精度是有限制的。对于大多数合理的货币值来说,这应该是可以的。只要您的货币小于 2 53(以美分为单位)或90,071,992,547,409.91,您就不会看到任何问题。

2.51 + .01; // => 2.5199999999999996 
currency(2.51).add(.01); // => 2.52 

2.52 - .01; // 2.5100000000000002 
currency(2.52).subtract(.01); // 2.51

currency.js还支持多种字符串。这样,它就可以轻松地融入您的 UI,而无需进行字符串与数字之间的相互转换。

var c = currency("$1,234.56").add("890.12"); // 2124.68 
c.format(); // 2,124.68 

// Negative values 
currency("-$5,000").add(1234.56); // -3765.44 
currency("($5,000)").add(1234.56); // -3765.44

默认情况下,货币解析为一个string值。

如果需要访问原始数字,该值将存储为 和integerstring您可以使用.intValue或访问.value

// Get the internal values
currency(123.45).add(.1).value; // => 123.55
currency(123.45).add(.1).intValue; // => 12355

方法

add

currency.add( value )

stringnumbercurrency值添加到当前货币实例。

currency(123.45).add(.01); // => "123.46"

subtract

currency.subtract( value )

从当前货币实例中减去stringnumber或值。currency

currency(123.45).subtract(.01); // => "123.44"

multiply

currency.multiply( number )

将当前货币实例乘以number

currency(123.45).multiply(2); // => "246.90"

divide

currency.divide( number )

将当前货币实例除以number

currency(123.45).divide(2); // => "61.73"

distribute

currency.distribute( number )

分配采用货币价值,并尝试均匀分配金额。分配后剩余的任何额外美分都将堆叠到第一组条目上。

currency(12.35).distribute(3); // => [4.12, 4.12, 4.11]
currency(12.00).distribute(3); // => [4.00, 4.00, 4.00]

format

currency.format([ function | options ])

返回人性化货币格式的简单格式化程序。

currency(1000.00).format(); // => "$1,000.00"
currency("1,234,567/90").add("200,000").format(); // => "$1,434,567.89"

可以通过传入选项作为第二个参数来覆盖默认格式化程序。

var euro = value => currency(value, { separator: ' ', decimal: ',', format: ... });

// ...

euro(1000.00).format(); // => "1 000,00"
euro(1234567.89).add("200 000").format(); // => "1 434 567,89"