您可以像这样使用 printf 方法:
System.out.printf("result = %.3f",number);
编辑(不使用printf
格式说明符)
void floatTruncate(float val){
float a = val;
String result = a + "";
int index = result.indexOf(".");
int zeroes = result.length() - 1 - index;
zeroes = 3 - zeroes;
for (int i = 1; i <= zeroes && zeroes < 3; i++) {
result = result + "0";
}
System.out.println("new result = " + result);
}
编辑2:(如果你只想保留3个小数位,如果你的输入就像number = 22.34567f
你想要输出一样,22.345
那么使用这个
void floatTruncate(float val) {
float a = val;
String result = a + "";
int index = result.indexOf(".");
int zeroes = result.length() - 1 - index;
//use this logic if ur logic is to keep only 3 decimal places
if(zeroes>3){
result = result.substring(0, index+4);
}
zeroes = 3 - zeroes;
for (int i = 1; i <= zeroes && zeroes < 3; i++) {
result = result + "0";
}
System.out.println("new result = " + result);
}
样本输出
a = 22.3f -> 22.300
a = 22.34f -> 22.340
a = 22.345f -> 22.345
a = 22.34567f -> 22.345