如何获得十进制部分的浮点数

时间:2016-12-31 07:10:19

标签: java

如何在Java中将浮点数的小数部分作为十进制数?

喜欢float f=2.34;

然后decimal part=34;

2 个答案:

答案 0 :(得分:1)

试试这个 -

float f=2.34;
float deci = (f - (int)f)*(Math.Pow(10,getDecimalPlaces(f));

getDecimalPlaces(Float f) {
   String txt = Float.toString(f):
   int integerPlaces = txt.indexOf('.'); 
   int decimalPlaces = txt.length() - integerPlaces - 1;
   return decimalPlaces;
}

答案 1 :(得分:0)

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static String getDecimalPart(double number, int numOfDigits){

        return String.format("%."+numOfDigits+"f", number-(int)number);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(getDecimalPart(2.454,2));
    }
}