PDA

View Full Version : Displaying amounts to 2 decimal places in JS


habib
09-24-2002, 01:22 PM
Hi

Is there a way of displaying numbers in 2 decimal places? I am using the function below to convert amounts to different currencies, and want to show the amount upto 2 decimal places. For example:

This amount 19.200000000000003 should be displayed as 19.20.

function convert_amount (amount) {
var input_amount = amount;
var sa_rate = 16;
var us_rate = 1.4;
var eu_rate = 1.6;

if (getCookie('home_location') == 'UK') {
return '£'+(input_amount); }
else
if (getCookie('home_location') == 'SA') {
return 'R'+(input_amount * sa_rate); }
else
if (getCookie('home_location') == 'US') {
return '$'+(input_amount * us_rate); }
else
if (getCookie('home_location') == 'EU') {
return '€'+(input_amount * eu_rate); }
}

chrismiceli
09-24-2002, 01:47 PM
here is a site explaining it all

http://javascriptkit.com/javatutors/round.shtml

here is a short explanation

var original=28.453

1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45

2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5

3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111

habib
09-24-2002, 02:14 PM
Hi,

Thanks for the link, how do I use this inconjunction with the above function?

mordred
09-24-2002, 03:08 PM
The example says

var original=28.453;
var result=Math.round(original*100)/100 //returns 28.45

and you have

var us_rate = 1.4;
return '$'+(input_amount * us_rate);

So just imagine that 'original' is now 'input_amount * us_rate'... hth.

You can also use Number.toFixed(), if you can ditch support for older browsers.

habib
09-24-2002, 03:26 PM
Thanks Mordred!

I tried it out and it works like a dream!

Thanks also Chrismiceli for pointing me into the right direction!


:thumbsup: