Home  >  Q&A  >  body text

javascript - Ask an interesting question: How to convert numbers into amount format

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)

曾经蜡笔没有小新曾经蜡笔没有小新2662 days ago916

reply all(3)I'll reply

  • PHP中文网

    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'

    reply
    0
  • 三叔

    三叔2017-07-05 11:04:21

    function toPrice(d){
    return `00${d}`.replace(/(.*)(\d{2})/g,'\.元').replace(/0*([1-9]*\d\..*)/,'')
    }

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-05 11:04:21

    (1232/100).toLocaleString()

    reply
    0
  • Cancelreply