I was solving a problem which requires the output to be truncated and to my surprise I haven't been able to find a way to truncate numbers in java.
The output needs to be the a number followed by 6 decimal places.
What I want is
double truncate(double number,int places)
and the output to be
truncate(14/3.0) = 4.666666
.
but what I'm getting is
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
// rounds( 14/3.0 , 6 ) = 4.666667
With String.format
I get
String.format("%.6f", 14/3.0) = 4.666667
I also tried a solution that I found on stackoverflow that suggested using BigDecimal and that gave me the very same answer.
NumberFormat
also seems to work in the same way
java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(6);
System.out.println(f.format(14/3.0)); // 4.666667
Is there a built in method that does this or do I need to write my own using something like BigInteger? Is there something I'm doing wrong?
It's because you are not truncating but rounding:
long tmp = Math.round(value);
If you use a cast instead it should work:
long tmp = (long) value;
So the code below outputs 4.666666
as you expect:
public static void main(String[] args) throws Exception {
System.out.println(truncate(14/3.0, 6));
}
public static double truncate(double value, int places) {
if (places < 0) {
throw new IllegalArgumentException();
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = (long) value;
return (double) tmp / factor;
}