我尝试在Java中仅将小数点后的2位数字进行最后2位四舍五入。 这是我的代码:-
val df = DecimalFormat("#.##")
val gh = df.format(19.14966566)
df的ans = 19.15
但是我只想要19.14,因为它是19.14966566的最后2位,没有四舍五入
答案 0 :(得分:1)
您可以使用以下代码
double x = 19.14966566;
double y = Math.floor(x * 100) / 100;
O/P-> 19.14
以您的代码样式
val df = 19.14966566
val gh = Math.floor(x * 100) / 100
gh-> 19.14
您也可以引用此链接:https://stackoverflow.com/a/32303271/6838146
让我知道您是否遇到任何问题
答案 1 :(得分:0)
您可以尝试...对我有用...
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.FLOOR
val gh = df.format(19.14966566)
答案 2 :(得分:0)
使用NumberFormat
为您提供另一种解决方案。
使用NumberFormat
,您可以显式设置:
赞:
val nf = NumberFormat.getInstance(Locale.US)
nf.minimumFractionDigits = 2
nf.maximumFractionDigits = 2
nf.roundingMode = RoundingMode.DOWN
val gh = nf.format(19.14966566)
println(gh)
将打印:
19.14