tags:

views:

94

answers:

1

In cpp file I have std::round(double)

Please can I know the equivalent code in Java

Edit: I am already using java.lang.Math.round(double) and getting match in 99% cases. But in some places iam getting mismatch. For example:

  • std::round(4816.5058) = 4816 and Math.round(4816.5058) = 4817
  • std::round(4466.49996) = 4467 and Math.round(4466.49997) = 4466
+8  A: 

java.lang.Math.round(double)

skaffman
iam already using java.lang.Math.round(double) and getting match in 99% cases. But in some places iam getting mismatch. for example std::round(4816.5058)= 4816 Math.round(4816.5058) = 4817 example 2: std::round(4466.49996) = 4467 Math.round(4466.49997) = 4466
@user462475: For your future questions: Please don't hide such important details like the one in your above comment when you ask your question.
0xA3
Your examples at least from the java side look correct to me. If anything I would say the results from c++ look wrong. It looks like Java in this instance is more precise.
Kevin D
@user462475: `double` types, in general, tend to have more precision than they do accuracy. It looks like your C++ results are actually wrong (according to half-up rounding; there are other kinds), I'm guessing because of accuracy issues. The Java `double` type also has accuracy issues, though apparently they're not showing up in your two examples (as the half-up rounding is correct). (Java offers other number types for perfect accuracy, notably `BigDecimal`. But you lose some speed, which is why "traditional" `double` types have accuracy limitations.)
T.J. Crowder
+1 @Kevin D and @0xA3: This happens many times that the important part why the users comes to ask question at SO is hid.
JavaGeek
@user462475: Just for completeness: If you want more control over the rounding process, you might look at `BigDecimal`'s `setScale` and `round` methods. They let you specify what kind of rounding you want (although again, for ordinary half-up rounding, Java's answers in your examples are correct): http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
T.J. Crowder