14

I want to truncate a float and a double 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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Azfar
  • 317
  • 1
  • 4
  • 14
  • Take a look at: http://stackoverflow.com/questions/1976809/are-there-any-functions-for-truncating-a-double-in-java – BeRecursive Apr 26 '12 at 11:36
  • 1
    Formatted printing is not the same thing as truncation. Truncation alters the data value. Your use of the term “truncate” is incorrect and misleading. I suggest you edit the title and body of your Question appropriately. For those readers looking for true truncation, see [*Are there any functions for truncating a double in java?*](https://stackoverflow.com/q/1976809/642706) as [commented by BeRecursive](https://stackoverflow.com/questions/10332546/truncate-a-float-and-a-double-in-java#comment13305233_10332546). – Basil Bourque Dec 30 '20 at 08:27

6 Answers6

27

try this out-

DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));

Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.

The expected result is:

12.49
12.45
12
Kshitij
  • 8,474
  • 2
  • 26
  • 34
4
double d = <some-value>;
System.out.println(String.format("%.2f", d - 0.005);
Prizoff
  • 4,486
  • 4
  • 41
  • 69
4

I have the same problem using Android, you can use instead:

DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);

but for this API Level 9 is required.

Another fast solution is:

double number = 12.43543542;
int aux = (int)(number*100);//1243
double result = aux/100d;//12.43
enkara
  • 6,189
  • 6
  • 34
  • 52
titusfx
  • 1,896
  • 27
  • 36
2

take a look with DecimalFormat() :

DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
Gwenc37
  • 2,064
  • 7
  • 18
  • 22
revo
  • 540
  • 1
  • 5
  • 15
1

Check java.math.BigDecimal.round(MathContext).

Gwenc37
  • 2,064
  • 7
  • 18
  • 22
Torben
  • 3,805
  • 26
  • 31
0

Try using DecimalFormat and set the RoundingMode to match what you need.

ChadNC
  • 2,528
  • 4
  • 25
  • 39