0
votes

I have some float variables in my java program:

float var1=1.23456f;
float var2=2.34567f;

In my calculations, the number of digits after decimal point in my float variable increases and decreases to maintain precision. for e.g. after some calculations System.out.println(var1); may print:

6.35

or

9.4500082E

or

88.25214

I want to round off these values to 3 decimal places and drop the subsequent decimal digits so that float gets rounded off like:

6.350   9.450   88.252

As far as i know, The NumberFormat and String.format() return the output as formatted String. How can i get the output as rounded off float to use it further in my calculations? Can i apply a rule to my float(Float) variables(Instance) to always round-off/drop the trailing digits after 3 decimal places?

3
You can't express every number of a float or even a double. What would you have the program do in that case? Find the closest number that can be represented to 3dp? This would cause massive rounding error...Boris the Spider
No, you can't get a "rounded off float." A float doesn't store a decimal number.Louis Wasserman
If numbers of decimal digits are really important for your code, consider using BigDecimal instead of float. Or use an int or long representing the number of thousandths.Patricia Shanahan
If you are trying to implement arithmetic with a fixed (or semi-fixed: fixed at times but changing occasionally) number of decimal digits in floating-point, then please do not. For a fixed number of digits, use fixed-point arithmetic. (The name is a huge clue about what it is suited for.) If you are trying to track accuracy somehow, then let the floating-point numbers float (again, the name is a clue) and track accuracy separately (or calculate bounds on it in advance).Eric Postpischil

3 Answers

4
votes

No, you can't get a "rounded off float." A float doesn't store a decimal number. Use BigDecimal if you want to do calculations using a specific number of decimal digits.

None of the other answers will get you what you actually want.

-1
votes

One (not very efficient) way to do it is to still use the NumberFormat class to return the String (with 3 digits) and then use Float.parseFloat() to turn it back into a float.

-1
votes

Use a simple helper method to round on arbitrary position:

 public static void main(String[] args) throws IOException {
    float fl = 1.2345f;
    System.out.println(round(fl, 3));
}

public static float round(float source, int positions) {
    long multiplier = (long) Math.pow(10, positions);
    return return ((float)((int) (source * multiplier)) / multiplier);
}

Please be aware, that thi snippet only demonstrates the idea and is limited to ~ 18 positions due to long overflow.