Several methods of preserving post-decimal digits in Java

Source: Internet
Author: User

A few recent experiments, some of which require that the data submitted by the form be converted to double, is a simple function that is straightforward and straightforward double.parsedouble (Request.getparameter ("Chinese"). Trim ()) can be achieved, But because it is statistical results, so need to retain two decimal places, so a variety of Baidu found a lot of solutions, here deliberately summarized under, in case later used again?

returns the double type of the

1. Can be rounded

1 double d = 114.145; 2 D = (double) Math.Round (d * +)/+; 3 System.out.println (d);

2. Bigdecimal.round_half_up means rounding, Bigdecimal.round_half_down is also five six in, bigdecimal.round_up means carry processing (is directly plus 1), Bigdecimal.round_down means to remove the mantissa directly.

1 double d = 114.145; 2 New BigDecimal (d); 3 D = B.setscale (2, bigdecimal.round_half_up). Doublevalue ();         4 System.out.println (d);
Returns a string of type

1.#.00 means to retain the post two bits, it is processed by directly cutting off the mantissa, not rounding.

1 double d = 114.145; 2 New DecimalFormat ("#.00"); 3 String str = Df.format (d); 4 System.out.println (str);

2.%.2f means that after two bits are retained, it is handled in a way that is also directly truncated and not rounded.

1 double d = 114.145; 2 String.Format ("%.2f", D);

3.roundingmode.half_down six, negative number first to take the absolute value and then five six into the negative, roundingmode.half_up: for rounding, negative number first to take the absolute value of five six into the negative.

1 double d = 114.1452 numberformat nf = numberformat.getnumberinstance (); 3 // keep two decimal places 4 nf.setmaximumfractiondigits (25//  If rounding is not required, you can use Roundingmode.down  6nf.setroundingmode (roundingmode.up); 7 System.out.println (Nf.format (d));

Several methods of preserving post-decimal digits in Java

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.