Using some methods in Java to round up will appear and expect different results, because these methods use the principle of actually: four six into five, five after the non-zero into one, five after the zero look at the odd even, five ago for I should shed, five ago for odd to go into one.
1. Four six in five when considering a situation where five occurs
Double f=9.545d; System.out.println (new BigDecimal (f). Setscale (2,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ()); System.out.println (New Java.text.DecimalFormat ("#.00"). Format (f)); System.out.println (); f=9.555d; System.out.println (new BigDecimal (f). Setscale (2,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ()); System.out.println (New Java.text.DecimalFormat ("#.00"). Format (f)); System.out.println (); f=9.5551d; System.out.println (new BigDecimal (f). Setscale (2,BIGDECIMAL.ROUND_HALF_UP). Doublevalue ()); System.out.println (New Java.text.DecimalFormat ("#.00"). Format (f)); Operation Result: 9.549.549.559.559.569.56
2. Five of cases when rounding occurs
Double f=9.545d; System.out.println (String.Format ("%.2f", f)); System.out.println (Math.Round (f*100) *0.01); System.out.println (); f=9.555d; System.out.println (String.Format ("%.2f", f)); System.out.println (Math.Round (f*100) *0.01); System.out.println (); f=9.5551d; System.out.println (String.Format ("%.2f", f)); System.out.println (Math.Round (f*100) *0.01); Operation Result: 9.559.559.569.569.569.56
So, in the case of running from the top, if you need to strictly observe rounding, you need to use the second case. (PS: By the way, JS in the use of toFixed is actually Sicherius five considerations, if you want strict rounding, you can use (Math.Round (a*100)/100). toFixed (2). But MySQL's round method is rounded)
This article is from the "Stuffed Pig" blog, please be sure to keep this source http://zuohao1990.blog.51cto.com/6057850/1971437
Java keeps rounding after decimal points