I suddenly had a need to just chop off the excessive digits off of a float number, so I looked in the toolbox and saw that DecimalFormat
was available.
Though creating a new object just to chop off some extra digits off a number seemed rather expensive, so I threw together a small program to test it.
public class Snippet {
static float unformatted = -542.347543274623876F;
static int fractionDigits = 2;
public static void main(String[] args){
long a = System.nanoTime();
System.out.println(stringMethod(unformatted));
long b = System.nanoTime();
System.out.println(formatMethod(unformatted));
long c = System.nanoTime();
System.out.println(stringMethod2(unformatted));
long d = System.nanoTime();
System.out.println("OP1:"+(b-a));
System.out.println("OP2:"+(c-b));
System.out.println("OP3:"+(d-c));
}
private static float stringMethod(float number){
String unfStr = String.valueOf(number);
for(int i=0;i<unfStr.length();i++){
if(unfStr.charAt(i) == '.'){
return Float.parseFloat(unfStr.substring(0, i+1+fractionDigits));
}
}
return Float.parseFloat(unfStr);
}
private static float stringMethod2(float number){
String unfStr = String.format("%."+(fractionDigits+1)+"f",number);
return Float.parseFloat(unfStr.substring(0,unfStr.length()-1));
}
private static float formatMethod(float number){
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(fractionDigits);
df.setRoundingMode(RoundingMode.DOWN);
return Float.parseFloat(df.format(unformatted));
}
}
OUTPUT:
-542.34
-542.34
-542.34
OP1:1937181
OP2:32609426
OP3:3111908
No matter how many times I run it, the DecimalFormat
method just can't keep up.
So I guess the question here is, is there any reason (apart from code readability) to use DecimalFormat
instead of creating your own method for simple float truncation?