I encountered an interesting problem while doing business recently:
In order to calculate money accurately, the server converts money into units (1 yuan = 100)
You need to convert it to money format at the front end 159 => 1.59 yuan
After looking at the project, the implementation method is to use tofixed, but there are bugs.
Require
159 -> 1.59元
1500 -> 15.00 元
88 -> 0.88元
8 -> 0.08元
In addition, sometimes the display format is (yuan is larger, minutes is smaller)
PHP中文网2017-07-05 11:04:21
A simple example is as follows:
function convertUnit (value) {
// bug 常见出现自 parseInt 未指定进制
return parseFloat(parseInt(value, 10) / 100).toFixed(2) + '元'
}
Simple test case:
> parseFloat(169 / 100).toFixed(2)
'1.69'
> parseFloat(8 / 100).toFixed(2)
'0.08'
> parseFloat(88 / 100).toFixed(2)
'0.88'
> parseFloat(1500 / 100).toFixed(2)
'15.00'
三叔2017-07-05 11:04:21
function toPrice(d){
return `00${d}`.replace(/(.*)(\d{2})/g,'\.元').replace(/0*([1-9]*\d\..*)/,'')
}