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.
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.
From the java docs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
A similar (answered) question:
http://www.java-forums.org/advanced-java/4130-rounding-double-two-decimal-places.html
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?
System.printf("%.1f", number);
String
: String.format("%.1f", number);
and assign it to a String reference variable.double
variable: number = (int) (number * 10) / 10.0;
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.