Hi All,

I need to trunk a float number with one decimal place. For eg: i have a float number called total=95.20004. my result should be 95.2. I have tried with the DecimalForma, but it is not working out. Kindly help me to resolve this issue.

You should be more specific as to what you want to do with your truncated number.
Do you want to put it in a `String`? Do you want to print it to the screen and keep the exact value in your variable? Do you want to truncate the result in …

All 4 Replies

I think you getting a error like

``````possible loss of precision
``````

Because you have a float number called total=95.20004

But actuallly the total is not float it is double value.
First you take total as a double value and use

``````DecimalFormat(##.#)
``````

on it you will get desired output OR
It you want total as float then take total=95.20004f
try this code
import java.text.DecimalFormat;

``````public class DecimalPlaces {
public static void main(String[] args) {
float f = 95.20004f;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(f));
}
}
``````

Hello you can use the printf();

``````float num = 1.23456;
System.out.printf("the float number is: %.1f",num);
``````

%f prints the full float number
%.1f prints 1 decimal
%.2f prints 2 decimal
%.3f prints 3 decimal
etc ....

You should be more specific as to what you want to do with your truncated number.
Do you want to put it in a `String`? Do you want to print it to the screen and keep the exact value in your variable? Do you want to truncate the result in your `double` variable?

1. Only printing to the screen: `System.printf("%.1f", number);`
2. Truncated number as a `String`: `String.format("%.1f", number);` and assign it to a String reference variable.
3. Truncate the result in your `double` variable: `number = (int) (number * 10) / 10.0;`
commented: Yup, intended usage is important. +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.