Madeyedexter
Madeyedexter

Reputation: 1193

Drop trailing digits of a floating point number

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?

Upvotes: 0

Views: 1448

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198103

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.

Upvotes: 4

Jk1
Jk1

Reputation: 11443

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.

Upvotes: -1

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.

Upvotes: -1

Related Questions