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.

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


I have the following code :

NumberFormat nf = NumberFormat.getInstance();

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 !!!!

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:

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.

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:

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

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.

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.