需求:
根据小数点后第二位,判断大于5进位,小于等于5则将第二位替换为5。
本人一遍没有写完善,这里贴出后期完善后的代码(欢迎各位提供漏洞)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
/**
* 根据小数点第二位,进行判断
* @author 章力
* @email zl0828@yeah.net
*/
public
static
String round(BigDecimal bgd){
// 只获取小数点后两位
DecimalFormat dfmt =
new
DecimalFormat(
"0.##"
);
String bgdStr = dfmt.format(bgd);
// 小数点下标
int
idx = bgdStr.indexOf(
"."
);
if
(idx>
0
){
// 整数部分
String intStr = bgdStr.substring(
0
,idx);
// 小数点后第1位数
String postOne = bgdStr.substring(idx+
1
, idx+
2
);
// 规则计算后的数值
String newNumU = dfmt.format(Double.parseDouble(intStr+
"."
+postOne)+
0.1
);
String newNumD = intStr+
"."
+postOne+
"5"
;
// 小数点后只有一位小数,默认第二位是零>小于5,直接替换为5
int
postnL = bgdStr.length()-(idx+
1
);
if
(postnL<
2
){
return
newNumD;
}
// 小数点后有第二位,进行规则判断
// 大于5,向上进位
// 小于等于5,直接替换为5
int
postTwo = Integer.parseInt(bgdStr.substring(idx+
2
));
if
(postTwo>
5
){
return
newNumU;
}
else
{
return
newNumD;
}
}
else
{
return
bgdStr+
".05"
;
}
}
|
本文转自 沫沫金 51CTO博客,原文链接:http://blog.51cto.com/zl0828/1420043,如需转载请自行联系原作者