1

I am trying to round float number but with certain condition. If second decimal point larger or equal 9 round up end else round down. Can you please help me this?

        //0.56 -> 0.5
        //1.56 -> 1.5
        //1.58 -> 1.5
        //1.59 -> 1.6
        //15.56 -> 15.5
Dim
  • 4,527
  • 15
  • 80
  • 139

5 Answers5

3

To round up at 0.09, and round down at 0.089999999..., you add 0.01 and truncate to 1 fractional digit.

Truncating positive floating point values can be done using the Math.floor() method, like this:

Math.floor(value * 10 + 0.1) / 10

UPDATE

Since a number like 0.59 is actually 0.58999999999999996, it gets rounded down, when the intent is to round up.

One way to get around "broken floating point math", is to use BigDecimal:

BigDecimal.valueOf(value).add(new BigDecimal("0.01")).setScale(1, RoundingMode.DOWN)

If you do this a lot, the new BigDecimal("0.01") value should be created as a static final constant.

Note: As with the first solution, this only works for positive numbers.

Andreas
  • 154,647
  • 11
  • 152
  • 247
2

This works good.

float n = 1.7912f;
n = n*100.0f;
long a = (int) n;
if (a % 10 >=9) {
    a=a+1;
} 
n =  (float) a / 100.0f;
System.out.println(n);
1

One of the different solution would be to check the last digit.

float number = number*100;
if (number % 10 >=9) {
    number = number + (10-(number % 10));
} else {
    number = number - (number % 10);
}
number = number / 100;
Ascor8522
  • 139
  • 1
  • 3
  • 11
0

Here's my homemade solution. Make a substring of the float's string value which starts two characters after the decimal and ends three characters after the decimal (would look like this: inputString=".56" subString="6"). Get the integer value of that substring and compare it to 9. If it is greater than or equal to, add another tenth. Otherwise trim the float from the hundredths place and move on. It's not very pretty, but it works:

public static void main(String[] args) {
    long current = System.currentTimeMillis();
    System.out.println(doWierdOperation(0.56F) + " - " + (System.currentTimeMillis()-current) + "ms.");
    current = System.currentTimeMillis();
    System.out.println(doWierdOperation(1.56F) + " - " + (System.currentTimeMillis()-current) + "ms.");
    current = System.currentTimeMillis();
    System.out.println(doWierdOperation(1.58F) + " - " + (System.currentTimeMillis()-current) + "ms.");
    current = System.currentTimeMillis();
    System.out.println(doWierdOperation(1.59F) + " - " + (System.currentTimeMillis()-current) + "ms.");
    current = System.currentTimeMillis();
    System.out.println(doWierdOperation(15.56F) + " - " + (System.currentTimeMillis()-current) + "ms.");
}


public static float doWierdOperation(float val) {
    String sValue = String.valueOf(val);
    int dec =  sValue.indexOf(".");
    if (sValue.charAt(dec + 2) == '9') {
        // Increment at tenths palce
        val += 0.1F;
    }
    // Trim from hundredth place
    return Float.valueOf(String.valueOf(val).substring(0, dec + 2));
}

First run:

0.5 - 3ms.
1.5 - 0ms.
1.5 - 0ms.
1.6 - 0ms.
15.5 - 0ms.

Second run:

0.5 - 3ms.
1.5 - 0ms.
1.5 - 0ms.
1.6 - 0ms.
15.5 - 0ms.

Third run:

0.5 - 2ms.
1.5 - 0ms.
1.5 - 0ms.
1.6 - 0ms.
15.5 - 0ms.
Cardinal System
  • 2,749
  • 3
  • 21
  • 42
  • Down-vote for using slow `String.valueOf(val)` 5 times and slow `.indexOf(".")` 3 times per call, and for using `float`, and for using `parseInt(substring) >= 9` when `charAt() == '9'` would be better and faster. Very inefficient and redundant code. – Andreas Dec 28 '17 at 19:02
  • @Andreas `charAt() == '9'` will not work because the OP is testing **greater than** or equal. – Cardinal System Dec 28 '17 at 19:04
  • What single-digit number is greater than 9? `>= 9` and `== 9` is the same thing, for **single**-digit numbers. – Andreas Dec 28 '17 at 19:05
  • @Andreas I feel like a moron for forgetting that I use a base ten number system. – Cardinal System Dec 28 '17 at 19:09
  • @Andreas I compared our answers. Your's takes 2 milliseconds more than mine to complete. Thank you for the parsing tips. – Cardinal System Dec 28 '17 at 19:23
  • Much better, but code will fail if called with a number that doesn't have 2+ decimals, e.g. an integer like `42`, and you should still change `float` to `double`, since numbers in question are `double` literals. – Andreas Dec 28 '17 at 19:27
  • @Andreas am I missing something? I'm pretty sure this says float: https://i.imgur.com/x19ecbL.png – Cardinal System Dec 28 '17 at 19:31
  • I guess that's difference in interpretation. Does "float number" mean "number of type `float`", or does it mean "a floating-point number"? Since `float` is rarely used, and "float" is a common abbreviation for "floating-point", I chose second interpretation. --- Your code still fails for `42` though, and the word is spelled "weird", not "wierd". *(Unless that was a joke?)* – Andreas Dec 28 '17 at 19:45
  • @Andreas I'll ask the OP, that way I can provide the best answer I possibly can. – Cardinal System Dec 28 '17 at 19:49
-3

Math.round() will do the trick

decodedxclusive
  • 401
  • 4
  • 8