Java keeps rounding after decimal points

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.