javascript - Ask an interesting question: How to convert numbers into amount format
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-07-05 11:02:21
0
3
952

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)

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(3)
Ty80

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'
三叔
function toPrice(d){
return `00${d}`.replace(/(.*)(\d{2})/g,'\.元').replace(/0*([1-9]*\d\..*)/,'')
}
世界只因有你
(1232/100).toLocaleString()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template