0

New to Java, relatively new to programming. The code below is the last couple lines of a program that already runs perfectly -- I just want to round the end result (the newTuition variable) and limit it to two significant figures.

newTuition, TUITIONINCREASE and tuition are all doubles.

    newTuition = ((TUITIONINCREASE * .01) * tuition) + tuition + ".");
    System.out.println("Your current tuition is $" + tuition + ". It will rise next year by " + TUITIONINCREASE + "% and " +
    "your new tuition will be $" + newTuition);
  • 1
    Welcome to SO: You say you are relatively new to programming, so here's a free lesson: Don't use floating point types to store monetary values. (Google it for a zillion explanations of why) – John3136 Jul 12 '12 at 06:03
  • You can refer to [this thread][1]. [1]: http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – Guanlun Jul 12 '12 at 06:03
  • Apart from the silly idea of using double to store money (as mentioned by @John3136) the first line of your code fails at compile time. Clearly you cannot append a "." to a double value end expect to get a double in return. Maybe `newTution` is `String` after all? – LisMorski Jul 12 '12 at 06:09
  • lismorski, yes, that period was a copy-paste error. Yes to all, I feel silly for using a floating point type for a monetary value now that you have all told it to me. We haven't yet learned anything about BigDecimal, and since this is the only line of code in which I use some of these variables/constants for calculation, I think the instructor will live. ;) – user1519533 Jul 12 '12 at 06:21
  • Thanks for the link Guanlun. I'll check it out. – user1519533 Jul 12 '12 at 06:22

2 Answers2

2

The commenters are correct. Do not use floating point numbers for this. What you need is the BigDecimal class. This will preserve precision for you during mathematical operations and contains methods for rounding and truncating.

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

jjathman
  • 12,536
  • 8
  • 29
  • 33
1

Use BigDecimal.Round: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#round(java.math.MathContext

Like this:

BigDecimal rounded = value.round(new MathContext(2, RoundingMode.HALF_UP));
System.out.println(value + ": " + rounded);
Luxspes
  • 6,268
  • 2
  • 28
  • 31