Question

I want to truncate a float value in Java.

Following are my requirements:

  1. if i have 12.49688f, it should be printed as 12.49 without rounding off
  2. if it is 12.456 in double, it should be printed as 12.45 without rounding off
  3. In any case if the value is like 12.0, it should be printed as 12 only.

Condition 3 is to be always kept in mind.It should be concurrent with truncating logic.

P.S: I am using Java 1.5 . So i know how to do it in Java 1.6 i.e using Decimal Format and calling setroundingMode () Method. I need to know for Java 1.5

Was it helpful?

Solution

Multiply, use Math#floor and divide before providing the number to the DecimalFormat. This is the same as cutoff roundig.

// Replace N with the desired number of decimals after the comma
number = Math.floor(1eN * number) / 1eN

This isn't perfect because of rounding errors in floating point calculation, so you will still have to specify N decimals to the DecimalFormat.

 

A (more expensive, but also more logical) alternative is to use a BigDecimal.

// Given as seperate statements for clarity, but these can be combined into a single line
// Replace "N" with the number of decimals after the comma
MathContext NDecimals = new MathContext(N, RoundingMode.FLOOR);
BigDecimal bdNumber = new BigDecimal(number, NDecimals);
number = bdNumber.doubleValue();

OTHER TIPS

Convert it to string and truncate anything after the second digit after the period. trim "0" and "." if having an "."

String x = Double.toString (12.456); // or Float.toString (12.49688f);

int pos = x.indexOf ('.');  // 
if (pos >= 0) {
  int end = Math.min(pos + 2, x.length() - 1); // truncate after 2 digits
  while (x.charAt (end) == '0') end --;  // trim 0
  if (x.charAt (end) == '.') end --; // trim .
  x = x.substring(0, end + 1);       // really truncate
}

(tested, works in my environment)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top