We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,585 Members — Technology Publication meets Social Media

# Inputting a float that stays at two decimal places

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...:");
x = otherFunction(f);
``````

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

Cheers

3
Contributors
4
Replies
1 Day
Discussion Span
9 Months Ago
Last Updated
5
Views
Question
TarkiB
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Skill Endorsements: 0

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.

JamesCherrill
... trying to help
Moderator
8,497 posts since Apr 2008
Reputation Points: 2,583
Skill Endorsements: 29

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

System.out.println(df.format(someFloat));
``````

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

Krokcy
Junior Poster in Training
55 posts since Sep 2010
Reputation Points: 24
Skill Endorsements: 0

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.

Cheers

TarkiB
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Skill Endorsements: 0

Anyway, problem solved.
Good! Now please mark this thread "solved" so everybody knows its status.

JamesCherrill
... trying to help
Moderator
8,497 posts since Apr 2008
Reputation Points: 2,583