i want float value of 3 fraction di开发者_如何学Pythongits 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?
Use the DecimalFormat class.
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.
Wouldn't (int)(f*1000)/1000.0 work? That seems clearer to me than the other suggestions.
Use DecimalFormat with setRoundingMode(RoundingMode.FLOOR)
As mentioned before, You can use DecimalFOrmat
DecimalFormat df= new DecimalFormat("##.###");
//##.### specifies the format that you want
String temp=df.format(var_name);
精彩评论