1

So as the top says. I am stuck on a rather simple problem but its seems I am stuck.

Example: x = 3.141

When I use printf("x is: %.2f", x); it spits out: X is 3.14

Well to calculate state tax anything above a cent needs to be rounded up so 3.141 should be 3.15. Is there a simple printf I can modify or an additional tag I can add? Or will I need to go a round about way to calculate the additional bit?

L.Spillner
  • 1,772
  • 10
  • 19
Epsilon52
  • 13
  • 3
  • 2
    Possible duplicate of [Java Round up Any Number](https://stackoverflow.com/questions/4540684/java-round-up-any-number) –  Apr 20 '18 at 14:02
  • i guess it would be a duplicate if you could math.ceil a specific decimal limit. but not exactly the same different need. – Epsilon52 Apr 20 '18 at 14:37

4 Answers4

3

The easiest thing would be to add 0.005 to the number.

PS: Make sure you calculate everything strictly in BigDecimal. Using double for money is not recommended.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
3

Instead of using printf, use a DecimalFormat with RoundingMode.CEILING:

DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
String rounded = df.format(x)
System.out.printf("x is: %s", rounded);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
0

This is a possible solution:

public static float roundUp(float num, int positions) {
    int tmp = ((int)(num*Math.pow(10, positions)));
    tmp = tmp + 10 - tmp%10;
    return ((float)(tmp/Math.pow(10, positions)));
}

You can obtain what you want by calling

roundUp(num, 3);

Or if you want a less-generic method, you can as well use:

public static float roundUp(float num) {
    int tmp = ((int)(num*1000.0f));
    tmp = tmp + 10 - tmp%10;
    return ((float)(tmp/1000.0f));
}
RaffoSorr
  • 405
  • 1
  • 5
  • 14
0
Math.ceil(x * 100) * 0.01

Avoids magic rounding numbers (do you need to add 0.9, or 0.99, or 0.999, etc)

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44