Java int相除保留两位小数
可以使用float或double类型来实现int相除保留两位小数的功能。具体实现方法如下:
- 将int类型转换为float或double类型,再进行相除操作。
例如:
int a = 10; int b = 3; float result = (float)a / (float)b; System.out.printf("%.2f", result);
这样可以得到相除结果保留两位小数的浮点数。
- 使用DecimalFormat类对相除结果进行格式化。
例如:
int a = 10; int b = 3; float result = (float)a / (float)b; DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(result));
这样可以得到相除结果保留两位小数的字符串。
原文地址: https://www.cveoy.top/t/topic/cpVZ 著作权归作者所有。请勿转载和采集!