How to get the decimal part of a float?

前端 未结 10 732
清酒与你
清酒与你 2020-11-28 10:43

I need to extract the decimal part of a float number, but I get weird results:

float n = 22.65f;
// I want x = 0.65f, but...

x = n % 1; // x = 0.6499996

x          


        
相关标签:
10条回答
  • 2020-11-28 10:47

    I bit long but works:

    BigDecimal.valueOf(2.65d).divideAndRemainder(BigDecimal.ONE)[1].floatValue()
    
    0 讨论(0)
  • 2020-11-28 10:57

    Because not all rational numbers can be represented as a floating point number and 0.6499996... is the closest approximation for 0.65.

    E.g., try printing first 20 digits of the number 0.65:

     System.out.printf("%.20f\n", 0.65f);
    

    ->

     0.64999997615814210000
    

    edit
    Rounding errors, which accumulate during computations, also play a part in it, as others noted.

    0 讨论(0)
  • 2020-11-28 10:57

    Try java.math.BigDecimal.

    0 讨论(0)
  • 2020-11-28 11:01

    Try this. If timer is 10.65 then h ends up as the first two decimal places * 100 = 65.

    This is a quick and easy way to separate what you want without the rounding issues.

    float h = (int)((timer % 1) * 100);
    
    0 讨论(0)
  • 2020-11-28 11:02

    I think this would be the most simple way :

    float n = 22.65f;
    float x = n - (int) n;
    
    0 讨论(0)
  • 2020-11-28 11:04

    This code will work for any number of decimal digits.

    float f = 2.3445f;
    String s = Float.toString(f);
    char[] c = s.toCharArray();
    int length = s.length();
    int flag = 0;
    StringBuilder n = new StringBuilder();
    for(int i = 0; i < length; i++)
    {
        if(flag == 1)
        {
            n.append(c[i]);
        }
        if(c[i] == '.')
        {
            flag = 1;
        }
    }
    String result = n.toString();
    int answer = Integer.parseInt(result);
    System.out.println(answer);
    
    0 讨论(0)
提交回复
热议问题