Home arrow static arrow Java Programming [Archive] - rounding double
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - rounding double
This topic has 3 replies on 1 page.

Posts:2
Registered: 6/21/04
rounding double  
Jun 21, 2004 10:42 AM



 
hi,

I have the following code :

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);

String fTax1 = nf.format( 1.245 );
String fTax2 = nf.format( 1.255 );
String fTax3 = nf.format( 1.265 );

the results are :
fTax1 = 1.24
fTax2 = 1.26
fTax3 = 1.26

Can anyone help me to answer that ???

Thanks !!!!
 

Posts:2,399
Registered: 10/26/00
Re: rounding double  
Jun 21, 2004 11:25 AM (reply 1 of 3)



 
strange and intriguing. I am not a numerical philosophy dude, but I can read some javadoc:
http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html

When you call NumberFormat.getInstance(), you will find that you actually get a DecimalFormat object. Scroll down the page in the link I provided and look for the heading "Rounding". There is a link there that explains the technique.
 

Posts:3,055
Registered: 18/06/98
Re: rounding double  
Jun 21, 2004 11:33 AM (reply 2 of 3)



 
Banker's rounding is being used here

It rounds the numbers to the nearest even digit - 1.245 rounds to 1.24, 1.255 rounds to 1.26, 1.265 rounds to 1.26.

From the javadocs of DecimalFormat and BigDecimal.ROUND_HALF_EVEN:

Rounding
DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting.

ROUND_HALF_EVEN
public static final int ROUND_HALF_EVEN
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
 

Posts:2
Registered: 6/21/04
Re: rounding double  
Jun 21, 2004 11:46 AM (reply 3 of 3)



 
Thanks a lot !!!
 
This topic has 3 replies on 1 page.