-3

Why is it not working?I want to "odleglosc" is 2.2 not 2.214354356

enter image description here

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mr.B
  • 1
  • `Math.round` doesn't round in place but returns a value. Since you never save the result to a variable, it is thrown away. – QBrute Feb 14 '18 at 11:53
  • you are not storing the value returned by Math.round(). Use codeXXX= Math.round(codeXXX) – akshaya pandey Feb 14 '18 at 11:54
  • Another way to state this is that Java is call-by-value, not call-by-reference. For your code to work, `Math.round(x)` would have to be a call-by-reference call. – Stephen C Feb 14 '18 at 12:00
  • This not work, because `Math.round` is int type, and it's rounding values by half up to the fully int value (not float/double). Let use `NumberFormat` class instead. – grabarz121 Feb 14 '18 at 12:04

3 Answers3

2

Math.round(argument) returns a number that is rounded from the argument.

In your example you ignore the returned value.

You probably meant to write:

 odleglosc = Math.round(odleglosc);
assylias
  • 321,522
  • 82
  • 660
  • 783
1
x = Math.round(x);

Otherwise if you just write Math.round(x); Java will make the calculation and have no variable to assign it to, and gets thrown away.

Oygen87
  • 81
  • 1
  • 9
0

Math.round() does not modify your variable because a double the value is passed to the function (compare all-by-value vs call-by-reference).

To round your value use

a = Math.round(a);
Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48