Java float 123.129456 to 123.12 without rounding

后端 未结 5 2101
一个人的身影
一个人的身影 2020-12-20 16:11

How do you cut down float primitive in java to two decimal places, without using rounding?:

123.99999 to 123.99
-8.022222 to         


        
5条回答
  •  被撕碎了的回忆
    2020-12-20 16:59

    First of all, there is no guarantee that just because a float can represent a.bcde exactly, it is guaranteed to be able to represent a.bc exactly.

    So if you're after just the printing part, how about doing it with some string-manipulation? Find the decimal point using indexOf and extract the part with two decimals, using substring.

提交回复
热议问题