Separating double into integer and decimal parts

前端 未结 11 1054
日久生厌
日久生厌 2020-12-06 10:20

I am trying to separate a double into the integer and decimal parts

So for example, the number 24.4 should be separated into 24 and 4.

int integer =          


        
相关标签:
11条回答
  • 2020-12-06 10:57

    Depending on the number of decimal digits, you could use this method:

    double number = 24.4;
    
    int integer = (int)number;
    double decimal = (10 * number - 10 * integer)/10;
    
    System.out.println(decimal); 
    

    Explanation: Remove the decimal points, do the subtraction, and finally return the decimal point back to its original location!

    0 讨论(0)
  • 2020-12-06 10:57

    You can do this:

    (val - val.longValue()) * 100
    

    use 1000 to get 3 fractions:

    for example:

    (1.2445 - 1) * 100 = 0.244
    
    0 讨论(0)
  • 2020-12-06 10:59

    First find the number the digits after the decimal point, and with that much number of 10's you have to multiply. eg: x=26.78621 then multiply by 100000[ here you can't multiply like x*10, again x*10 so on (5 times), the 1st time you multiply with 10, it will give you 267.862199999..] After multiplication subtract 2600000 from the result. here is a link of your answer which i have code it. https://stackoverflow.com/a/18517555/2508414

    0 讨论(0)
  • 2020-12-06 11:02
    double number = 20.57;
    Double.valueOf(String.valueOf(number)).intValue()
    
    0 讨论(0)
  • 2020-12-06 11:04
    float number = (float) 22.45;
    int integer = (int)number;
    double decimal = number-integer;
    System.out.println(integer + "decimal" + decimal); 
    
    0 讨论(0)
提交回复
热议问题