currency.js使用学习
github地址:github.com/scurker/cur…
currency.js 是一个轻量级的 ~1KB JavaScript 库,用于处理货币值。它旨在解决 javascript 中的浮点问题。Bartek Szopka 的这个演讲详细解释了为什么 javascript 有浮点问题。
安装
npm
npm install --save currency.js
yarn
yarn add currency.js
用法
Currency 将接受数字、字符串或 currency 对象本身作为值。
浮点数加减
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(123); // 123.00
currency(1.23); // 1.23
currency("1.23") // 1.23
currency("$12.30") // 12.30
var value = currency("123.45");
currency(value); // 123.45
算术运算
currency(123.50).add(0.23); // 123.73
currency(5.00).subtract(0.50); // 4.50
currency(45.25).multiply(3); // 135.75
currency(1.12).distribute(5); // [0.23, 0.23, 0.22, 0.22, 0.22]
内置的format
currency("2,573,693.75").add("100,275.50").format(); // "$2,673,969.25"
currency("1,237.72").subtract(300).format(); // "$937.72"
配置项Options
var euro = value => currency(value, { symbol: "€", separator: ".", decimal: "," });
euro("2.573.693,75").add("100.275,50").format(); // "€2.673.969,25"
euro("1.237,72").subtract(300).format(); // "€937,72"
symbol
默认值:$;
调用currency.format()时,包含的货币符号
separator
默认值:,;
调用currency.format()时,划分数字组的分隔符
decimal
默认值:.;
调用currency.format()时,小数的分隔符
precision
默认值:2;
调用currency.format()时,小数的位数
fromCents
默认值:false;
将 amount 值解析为次要货币单位(例如,以美元为单位的美分)而不是 dollars
工厂函数示例
const USD = value => currency(value, { symbol: "$", precision: 2 });
const JPY = value => currency(value, { symbol: "¥", precision: 0 });
const GAS = value => currency(value, { precision: 3 });
USD(1234.56).format(); // "$1,234.56"
JPY(1234.56).format(); // "¥1,235"
GAS(1234.56).format(); // "$1,234.560"