tags:

views:

116

answers:

4

Hi i want float value of 3 fraction digits after digit,i dont want to round of the value for example: float f=2.13275; i want f as 2.132 not 2.133 how can i do it in java?

+1  A: 

Use the DecimalFormat class.

matt b
Its the best possible thing, I guess.
Adeel Ansari
Won't this solution round rather than truncate?
Asaph
@Asaph, you can use different rounding modes, including RoundingMode.FLOOR or RoundingMode.DOWN.
matt b
+1  A: 

Math.floor() will chop off anything after the decimal point without rounding. You can play a trick where you multiply by the appropriate order of magnitude, floor the result and then divide by the same order of magnitude. Like this:

double f = 2.13275;
double f2 = Math.floor(f * 1000) / 1000;

Note: the Math class deals in doubles, not floats. If you really want floats, you can do some casting but there will be some loss of precision. On the other hand, you only want 3 decimal places so you probably won't mind.

Edit: @Jason S points out that negative numbers may have their last decimal place changed. I'm not sure if you want this or if it's even relevant in the context of your code. But if it is, there are a number of ways around it. One is to use Math.ceil() for the negative number case:

double f2 = (f < 0 ? Math.ceil(f * 1000) : Math.floor(f * 1000)) / 1000;

Yeah, I know, it's getting a little messy. But it illustrates the point.

Asaph
works perfectly for positive numbers. if you want to chop off w/o rounding for negative numbers, you need to use truncation rather than floor, or take the absolute value inside Math.floor() and multiply by the original number's sign afterwards.
Jason S
@Jason S: Good point about negative numbers.
Asaph
Hi it works for positive values but it not working for nagative float values
sanjana
can u tell me plz how to do truncation?
sanjana
@sanjana: I updated my answer to work for negative numbers.
Asaph
Thanks its working
sanjana
@sanjana: Good to hear. If my answer solved your problem, please mark it correct by clicking the checkbox beside the answer :)
Asaph
Its perfectly correct, but seems work around. I would suggest to use DecimalFormat instead, as 'matt b' suggested. You just cut that part off. Simple isn't it?
Adeel Ansari
@Vinegar: Won't matt b's solution round rather than truncate?
Asaph
A: 

Use DecimalFormat with setRoundingMode(RoundingMode.FLOOR)

Jim Garrison
But it won't work for negative numbers.
Asaph
+1  A: 

Wouldn't (int)(f*1000)/1000.0 work? That seems clearer to me than the other suggestions.

Mark Bessey
It's really the same concept as the Math.floor() solution. Anyway, the OP needs it to work for negative numbers and this answer doesn't address that requirement.
Asaph
It should do the right thing with negative numbers. That was kind of my point.
Mark Bessey
I just checked this, and it does have the right behavior. I was pretty sure that casting to int performed truncation, rather than rounding.
Mark Bessey