Keep 2 decimal digits, use Java.text.NumberFormat

Source: Internet
Author: User

Record 1. Keep Decimal

Two-bit decimal, Java method, using NumberFormat to achieve, rounding results

        Double Sourceprice = 4940.20;//Sourceprice = 1514940.20
        double reductionprice = 0.1;
        Double price = Sourceprice-reductionprice;
        NumberFormat NF = numberformat.getnumberinstance ();

        Notice here

        nf.setmaximumfractiondigits (2);
        System.out.println (Nf.format (price));

Output results:
(The result is one, in fact, the default is to remove the last 0.)
That is 4940.10, the final display 4940.1;
If the calculation result is 4940.00, then the final is 4940;

4,940.1

.

1,514,940.1 2. Separator

Note The separator, thousand separator, million separator, ...), which will display the separator directly, if you want to remove it, use
Nf.setgroupingused (FALSE);

The output turns into (no separator):

4940.1

.

1514940.1 3. Other ways to achieve

Double number = 12345.5593;//target value
SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-bigdecimal----------rounded--------------");

BigDecimal BigDecimal = new BigDecimal (number);
Double resnumber = Bigdecimal.setscale (2, bigdecimal.round_half_up). Doublevalue ();
System.out.println (Resnumber);

SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-decimalformat--------rounded----------------");
DecimalFormat DecimalFormat = new DecimalFormat ("#.00");
System.out.println (Decimalformat.format (number));

SYSTEM.OUT.PRINTLN ("---calculation-keep 2 decimal-string.format--------rounded----------------");
System.out.println (String.Format ("%.2f", number));

Output results:

12345.55

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.