Hi there,

I'm having trouble with floats in Java. My program accepts a number in the form of a float. The number typically has two decimals (but not always). It seems to work fine in most cases. For example, I could put in 54.67, and that number would be passed to another function. Great. However, my problem is this:

If I put in 54.60 as the number, it gets set as a float, which automatically rounds it to 54.6, and passes that to the other function. The other function doesn't work properly when this 0 is dropped. So my question is:

When using a float, how can I prevent the trailing 0 from being dropped? How can I prevent 54.60 from being turned into 54.6?

This is how I'm accepting input:

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
float f;
System.out.println("Enter number...:");
f = Float.valueOf(br.readLine()).floatValue();
x = otherFunction(f);

This has been driving me absolutely crazy, so any help would be really appreciated.


5 Years
Discussion Span
Last Post by JamesCherrill

This question makes no sense. Float values are held in binary, not decimal, and adding a trailing zero after the decimal point makes no difference to any numeric values.


As James said in your context it doesnt really make sense. However if you are printing the value you can use the DecimalFormat class, ie.:

DecimalFormat df = new DecimalFormat ("0.00");
float someFloat;

//some code


Not sure if there is a better/easier way, but this is how i normally do it.


Thanks for the responses. It turns out I was using float when I really shouldn't have been.

The method the number is getting passed to needs the trailing 0 to be there, otherwise it doesn't really work properly. To achieve this I used a double instead with some different code. For anyone interested, the relevant parts are as follows:

Scanner scan = new Scanner (System.in);
String numb = "";
System.out.println("Input number: ");
numb = scan.next();
double x = Double.parseDouble(numb);

Anyway, problem solved. Thanks again for the responses.


This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.