java四舍五入常用的2种方法
1.Math.round
Math.round ()是Java中舍入数字的经典方法,Math.round(变量名称)这种返回的其实是整数,也就是说四舍五入之后是整数。
该方法有以下几种语法格式:
long round (double d) int round (float f)
示例:
public class Test{ public static void main (string args[]){ double d = 100.675; double e = 100.500; float f = 100; float g = 90f; System.out.println(Math.round(d)) ; System.out.println(Math.round(e)); System.out.println(Math.round(f)); System.out.println(Math.round(g)); } }
输出结果为:
101 101 100 90
如果要输出百分比(记得乘100):
double p1 = (num_1 * 1.0) / total; System.out.println(Math.round(p1 * 100) + "%");
2.DecimalFormat
对Java中 DecimalFormat 的所有基础用法进行了一个汇总。 DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。0 表示如果位数不足则以 0 填充,# 表示只要有可能就把数字拉上这个位置。返回值为String类型 小数部分 #代表最多有几位,0代表必须有且只能有几位 .00 表示最终结果得有两位小数,没有,我给你加上;多了,就四舍五入第三个小数 .## 标示最终结果最多有两位小数 一位或者没有都可以 多了同样四舍五入第三位 整数部分 0 和 # 当整数部分为0时 比如 0.1 #此时认为整数部分不存在,所以不写 0 认为没有至少也得一位,写上0 这跟上面第一部分的表现是一致的:# 有就写,没有就不写 ;0 必须有 没有补0 整数部分有多位时: 2 20 200 由上面的结果可以看出 0和#对整数部分多位时的处理是一致的 就是有几位写多少位 这跟上面两部分的表现是不一致的 在有多位时,0和#都没有匹配位数,而是有多少写多少。
参考用法:
double pi = 3.1415927;//圆周率 //取一位整数 System.out.println(new DecimalFormat("0").format(pi));//3 //取一位整数和两位小数 System.out.println(new DecimalFormat("0.00").format(pi));//3.14 //取两位整数和三位小数,整数不足部分以0填补。 System.out.println(new DecimalFormat("00.000").format(pi));//03.142 //取所有整数部分 System.out.println(new DecimalFormat("#").format(pi));//3 //以百分比方式计数,并取两位小数 System.out.println(new DecimalFormat("#.##%").format(pi));//314.6% long c = 299792458;//光速 //显示为科学计数法,并取五位小数 System.out.println(new DecimalFormat("#.#####E0").format(c));//2.99792E8 //显示为两位整数的科学计数法,并取四位小数 System.out.println(new DecimalFormat("00.####E0").format(c));//29.9792E7 //每三位以逗号进行分隔。 System.out.println(new DecimalFormat(",###").format(c));//299,792,458 //将格式嵌入文本 System.out.println(new DecimalFormat("光速大小为每秒,###米。").format(c));//光速大小为每秒299,792,458米。
注意:计算百分数的时候最好传入double类型,而且不需要事先*100
int a=2; int b=3; System.out.println(new DecimalFormat("#%").format(a/b));//0% System.out.println(new DecimalFormat("#%").format((a*1.0)/b));//67% System.out.println(new DecimalFormat("#%").format((a*100.0)/b));//6667%
下一篇:
Java中的取整、四舍五入