前端處理金額精度問題和千分位格式化

  • 前端在處理金額時(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"
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容