1.数据:
-- 创建数据表
CREATE TABLE `count_test` (
`id` INT(20) PRIMARY KEY AUTO_INCREMENT,
`a` VARCHAR ( 255 ) DEFAULT NULL,
`b` VARCHAR ( 255 ) DEFAULT NULL
) ENGINE = INNODB DEFAULT CHARSET = utf8;
-- 插入几条数据
insert into count_test(a,b) values('31','72');
insert into count_test(a,b) values('22','88');
insert into count_test(a,b) values('99','9999');
2.保留2位小数:
select CONCAT(ROUND(a/b*100,2),"%")as s from count_test
ps:用round(x,d)函数 四舍五入指定保留位数,再用从concat(str,str)函数拼接 "%"
查询结果:
不保留小数(保留0位)
select CONCAT(ROUND(a/b*100,0),"%")as s from count_test
3.使用函数介绍:
concat() 函数:用于将两个或多个字符串拼接成一个字符串并返回,语法为“CONCAT(string1,string2, ... );”;该函数需要至少一个参数,否则会引起错误。concat()函数在拼接之前会将所有参数转换为字符串类型;如果任何参数为NULL,则CONCAT()函数返回NULL值。
round() 函数:在mysql中,round函数用于数据的四舍五入,语法为"round(x,d)" ,x指要处理的数,d是指保留几位小数 这里有个值得注意的地方是,d可以是负数。
4.java 保留小数位
public static void main(String[] args) {
int anomaly = 31;
int all =72;
String ratio = String.format("%.2f", ((float) anomaly * 100 / all));
System.out.println("百分比"+ratio);
}
运行结果:
ps:数学计算完成之后转换为 float(浮点)类型,再用String类的format()方法格式化需要保留的位数;
String.format("%.nf",args) n为需要几位小数,args 为要操作的数据.;