简体   繁体   中英

I am trying to convert numbers to currency and add numbers with 2 decimal points

I have a simple form that users input number values into (though the fields are text fields). I am trying to do 2 things:

The first is convert a number string (123456 or 123456.75) into a dollar value with 2 decimal places ($123,456.75) after the user leaves the field.

So user enters 123456.75 and on leaving the field it is converted to $123,456.75

The second related problem is to calculate 2 numbers and format the answer into a dollar value:

field1 = 24.75
field2 - 24.24

I need field3 to be $48.99

Here is what I have so far on the second problem (this script is tied to a button):

onclick="document.getElementById('field3').value = 
    parseInt(document.getElementById('field1').value) +  
    parseInt(document.getElementById('field2').value);" 

This gives me an answer but to 0 decimal places. (24.75 + 24.05 = 48)

Thanks in advance if you can help

parseInt will remove all decimal places. Try using parseFloat instead along with Math.round .

ex. (for 2 decimal places)

Math.round((parseFloat("24.75") * 100))/100

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM