aspose file tools*
The moose likes HTML, CSS and JavaScript and the fly likes Rouning floating numbers upto 2 decimal points Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Rouning floating numbers upto 2 decimal points" Watch "Rouning floating numbers upto 2 decimal points" New topic
Author

Rouning floating numbers upto 2 decimal points

amitesh kumar
Ranch Hand

Joined: Aug 01, 2006
Posts: 50
Hi,
I have to display values in rounded form. For example if a=23.4566777 then i have to round it to 23.45 . Please help me achieve this requirement. Currently I am using Math.round() method, which gives output as 23 , i.e. it removes the decimal values completely.

Thanks in advance
Amitesh
Jaikiran Pai
Marshal

Joined: Jul 20, 2005
Posts: 10033
    
163

Try this:



The toFixed method on Number accepts the number of decimal places, you want the precision

[ August 23, 2006: Message edited by: jaikiran pai ]
[ August 23, 2006: Message edited by: jaikiran pai ]

[My Blog] [JavaRanch Journal]
amitesh kumar
Ranch Hand

Joined: Aug 01, 2006
Posts: 50
Hi Jaikiran,
Thanks a lot. It works perfectly. I have found one more way. I first convert the num to string object. Then get the index of "." in that string. Now i take substring of the original string.


Anyways your approach is a better one and I have used that one only in my code.

Thanks again
Amitesh
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
Oh for the fun of it, a third way

var num = 12.3456789;
var roundNum = Math.round(num*100)/100;

Only problem with that way is we loose trailing zeros so you would have to convert it to a string and pad it. What a mess! lol

Eric
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Rouning floating numbers upto 2 decimal points