- 前端在處理金額時(shí),通常需要將金額保留兩位小數(shù),或者需要在前面添加金額符號,在相對專業(yè)的特定系統(tǒng)中或者看板中,需要將金額以3位一分割,從而便于閱讀。
- 介紹一個(gè)專門用于金額處理和格式化的npm庫: currency.js https://currency.js.org/
初始化
npm install --save currency.js
或
yarn add currency.js
用法
1. 金額保留小數(shù)處理
// 數(shù)字
currency(2); // => "2.00"
currency(250); // => "250.00"
// 小數(shù)
currency(2.00); // => "2.00"
currency(2.24); // => "2.24"
// 字符串
currency("1.23"); // => "1.23"
currency("$12.30"); // => "12.30"
currency("£1,234,567.89"); // => "1,234,567.89"
//設(shè)置保留位數(shù)()精度
currency(1.234, { precision: 2 }); // => "1.23"
currency(1.234, { precision: 3 }); // => "1.234"
2. 格式化金額()
currency(1.23).format(); // => "$1.23"
currency(1234.56, { separator: ',' }).format(); // => "1,234.56"
currency(1234.56, { separator: ' ' }).format(); // => "1 234.56"
3. 金額運(yùn)算(加減乘除)
currency(2.51).add(.01); // => 2.52
currency(2.52).subtract(.01); // 2.51
currency(45.25).multiply(3); // 135.75
currency(123.45).divide(2); // => "61.73"