public
class
RoundTool {
public
static
String round(
double
value,
int
dotNum) {
String strValue = String.valueOf(value);
int
pos = strValue.indexOf(
"."
);
int
len = strValue.length();
int
dotLen = len - pos -
1
;
String endNum =
""
;
if
(dotNum < dotLen) {
String c = strValue.substring(pos + dotNum +
1
, pos + dotNum +
2
);
int
cNum = Integer.parseInt(c);
double
tempValue = Double.parseDouble(strValue);
if
(cNum >=
5
) {
String tempDot =
""
;
for
(
int
i =
0
; i < dotNum -
1
; i++) {
tempDot = tempDot +
"0"
;
}
tempDot =
"0."
+ tempDot +
"1"
;
tempValue = tempValue + Double.parseDouble(tempDot);
strValue = String.valueOf(tempValue);
endNum = strValue.substring(
0
, strValue.indexOf(
"."
) + dotNum +
1
);
}
else
{
endNum = strValue.substring(
0
, strValue.indexOf(
"."
) + dotNum +
1
);
}
}
else
if
(dotNum == dotLen) {
endNum = String.valueOf(value);
}
else
{
for
(
int
i =
0
; i <= dotNum - dotLen -
1
; i++) {
strValue = strValue +
"0"
;
}
endNum = strValue;
}
return
endNum;
}
public
static
void
main(String[] args) {
System.out.println(
"数值123.121保留两位小数:\t"
+ RoundTool.round(
123.121
,
2
));
System.out.println(
"数值123.456789保留3位小数:\t"
+ RoundTool.round(
123.456789
,
3
));
System.out.println(
"数值123.1231保留3位小数:\t"
+ RoundTool.round(
123.1231
,
3
));
System.out.println(
"数值123.5保留3位小数:\t"
+ RoundTool.round(
123.5
,
3
));
}
}
网友评论