Rounding negative numbers in Java

后端 未结 6 956
予麋鹿
予麋鹿 2020-12-09 10:30

According to Wikipedia when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 10:53

    The Wikipedia article you cite does not say that's the only way to round, just the common way to round. Also mentioned in that article are several alternatives (unfortunately none of which describe Java's rounding method - even though they call it out as "Asymmetric Arithmetic Rounding" when indicating what JavaScript does).

    You need to decide how you want your numbers rounded, then use that method. If Java's implementation matches that, then great. otherwise you'll need to implement it on your own.

提交回复
热议问题