DecimalFormat rounding float type of pit

Source: Internet
Author: User

Today, stepping on a hole, using DecimalFormat to complete rounding, but the float type is passed in, several rounds of testing only to find a problem, the incoming float will be converted to double type, we all know that float is 4 bits, double is 8 bits, A strong turn is sure to cause progress loss.

Use the following method

  publicstaticformatMoney(floatvalue) {    new    DecimalFormat("####.#");        format.setRoundingMode(RoundingMode.HALF_UP);        return"¥" + format.format(value);    }
    1. Incoming 1.15 returns 1.1.
    2. Incoming 1.25 returns 1.3.

      Oh, that's weird. Format.format (value) receives the double type by default, I have now passed the float type, and there is no error, but it has been strongly turned to double type, 1.15 has been converted to 1.149999999 ... precision has been lost.

The solution uses BigDecimal to not lose progress by converting the float to a bit double

Modify method

  publicstaticfloatformatFloat(floatvalue) {        decimalnew BigDecimal(String.valueOf(value));        new DecimalFormat("####.#");        format.setRoundingMode(RoundingMode.HALF_UP);        return Float.parseFloat(format.format(decimal.doubleValue()));    }

Use Format.setroundingmode (ROUNDINGMODE.HALF_UP), you can control the way the conversion, specific documents can refer to the Java doc

DecimalFormat rounding float type of pit

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.