Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a float and a double in java [duplicate]

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.

like image 277
Azfar Avatar asked Apr 26 '12 11:04

Azfar


People also ask

How do you truncate a double value in Java?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.

Does float truncate?

Float#truncate() is a float class method which return a truncated value rounded to ndigits decimal digits precision.

What is truncate in Java?

In Java programming, truncation means to trim some digits of a float or double-type number or some characters of a string from the right. We can also truncate the decimal portion completely that makes it an integer.

How do you shorten a double?

There are two common abbreviations of double: dbl. and dubl.


2 Answers

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
like image 57
Kshitij Avatar answered Sep 19 '22 14:09

Kshitij


take a look with DecimalFormat() :

DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
like image 30
revo Avatar answered Sep 19 '22 14:09

revo