简体   繁体   中英

Java - Decimal Format Precision lost when returning a Float or Decimal

I have reviewed a number of threads related to formatting numbers. For the most part it works except for the value 3.101. Float and Double have been used along with the ## and 00 format.

import java.text.DecimalFormat;

public class DecimalFormatTest {
public static void main(String[] args) 
{
    Float d1 = -3.1011f;
    Double ds = -3.1011;
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.println (Double.valueOf(df.format(d1)));
    System.out.println (Double.valueOf(df.format(ds)));

    DecimalFormat df2 = new DecimalFormat("#.00");
    System.out.println (Double.valueOf(df2.format(d1)));
    System.out.println (Double.valueOf(df2.format(ds)));
 }
}

The output is :

-3.1
-3.1
-3.1
-3.1

Expected output :

-3.10
-3.10
-3.10
-3.10

As mentioned above, this works for all the other numbers I have tested. For some reason this is causing an issue.

Any ideas as to what makes this number so different and what extra step is needed to get the 2nd digit?

Keep in mind, the key is that I want to eventually return a Float or Double.

Try this.

public static void main(String[] args) 
    {
        Float d1 = -3.1011f;
        Double ds = -3.1011;
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println (df.format(d1));
        System.out.println (df.format(ds));

        DecimalFormat df2 = new DecimalFormat("0.00");
        System.out.println (df2.format(d1));
        System.out.println (df2.format(ds));
     }

This works:

Double number = 3.101;
System.out.printf("%.2f", number);

The main culprit here is Double.valueOf . Try removing it and it should work fine like below: Also, putting ("#.##") wil cause further problem . So rather use any ("0.00") at-least after precision.

import java.text.DecimalFormat;

public class DecimalFormatTest {
public static void main(String[] args) 
    {
        Float d1 = -3.1011f;
        Double ds = -3.1011;
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println (df.format(d1));
        System.out.println (df.format(ds));

        DecimalFormat df2 = new DecimalFormat("0.00");
        System.out.println (df2.format(d1));
        System.out.println (df2.format(ds));
     }
}

For reference : Double decimal formatting in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM