how does Java convert floats to strings

后端 未结 3 799
广开言路
广开言路 2021-01-03 04:11

Here\'s what I\'m looking at:

float p=1.15f;
BigDecimal bdp=new BigDecimal(p);
float q=1.1499999f;
float r=1.14999999f;

System.out.println(p);   //1.15
Syst         


        
3条回答
  •  情书的邮戳
    2021-01-03 04:53

    I think this is the relevant part of the Javadoc that describes the behavior you're looking at (from the static String toString(float) method):

    How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float.

    To paraphrase: the toString methods for floating-point types will generally produce the shortest decimal representation that can unabmiguously identify the true value of the floating-point number.

    Example program to illustrate:

    import java.math.BigDecimal;
    
    public class FloatTest {
    
      static void show(float f) {
        BigDecimal f_exact = new BigDecimal(f);
        System.out.println("---");
        System.out.println("String value: " + f);
        System.out.println("Exact value:  " + f_exact);
        System.out.println("Delta:        " + 
            new BigDecimal("1.15").subtract(f_exact));
      }
    
      public static void main(String[] args) {
        show(1.15f);
        show(Math.nextUp(1.15f));
      }
    }
    

    Output:

    ---
    String value: 1.15
    Exact value:  1.14999997615814208984375
    Delta:        2.384185791015625E-8
    ---
    String value: 1.1500001
    Exact value:  1.150000095367431640625
    Delta:        -9.5367431640625E-8
    

提交回复
热议问题