Rounding off numbers

D

davidchase314

Hi. I was just wondering how I could get the output of this bit of
Javascript to round up to two decimal places. My code is below. Thank
you.

"<script language="JavaScript">

<!--

var price1 = 2.99
var price2 = 13.98
var price3 = 8.95
var price4 = 1.99

var oprice = price1 + price2 + price3 + price4

document.write(oprice)
//-->

</script>"

The output I'm getting is 27.909999999999996

Thanks again.
 
E

Evertjan.

wrote on 16 aug 2006 in comp.lang.javascript:
Hi. I was just wondering how I could get the output of this bit of
Javascript to round up to two decimal places. My code is below. Thank
you.

"<script language="JavaScript">

<!--

var price1 = 2.99
var price2 = 13.98
var price3 = 8.95
var price4 = 1.99

var oprice = price1 + price2 + price3 + price4

document.write(oprice)
//-->

</script>"

The output I'm getting is 27.909999999999996

The de facto FAQ:

<http://www.merlyn.demon.co.uk/js-round.htm>
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Wed, 16 Aug 2006 10:24:01 remote, seen in
I was just wondering how I could get the output of this bit of
Javascript to round up to two decimal places.

In general, you want to round to nearest, not round up.

Before posting, you should read the newsgroup and its FAQ; your
situation is amply covered therein.

"<script language="JavaScript">

Omit first ". Attribute deprecated.
<!--

var price1 = 2.99
var price2 = 13.98
var price3 = 8.95
var price4 = 1.99

var oprice = price1 + price2 + price3 + price4

document.write(oprice)
//-->

</script>"

Omit ".
The output I'm getting is 27.909999999999996

Yes.

If you want an answer exact in pence, then you can work in pence.
Integers up to 2^53 are held exactly, but most decimal fractions are
not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top