如0.125 ==> 0.13再如 0.1==>0.10
涉及ASCII码转换 整型 char计算
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestIntDivide2Float {
public static void main(String[] args) {
double temp = 0.256983D;
String postfix = String.valueOf(temp);
if (postfix.charAt(4) >= '5') {
// 0.126
int t = postfix.charAt(3);
postfix = postfix.substring(0, 3);
char ch = (char) ((char) t + 1);
log.error("结果: {}", postfix + String.valueOf(ch));
}
String ret = solution(1133L, 5555L);
System.err.println("ret: " + ret);
}
public static String solution(long num, long divider) {
double a0 = num;
double b0 = divider;
double temp0 = a0 / b0;
System.err.println("整型相除结果:" + temp0);
if (num < divider) {
double a = num;
double b = divider;
double temp = a / b;
String postfix = String.valueOf(temp);
if (postfix.length() > 4) {
char ch = postfix.charAt(4) > '4' ? (char)(postfix.charAt(3) + 1) : '0';
if (ch != '0') {
char tempCh = (char)(postfix.charAt(3) + 1);
return postfix.substring(0, 3) + String.valueOf(tempCh);
}
return postfix.substring(0, 4);
}
if (postfix.length() == 4) {
postfix = postfix.substring(0, 4);
return postfix;
}
if (postfix.length() == 3) {
postfix = postfix.substring(0, 3);
return postfix + "0";
}
}
long longNum = num / divider;
long remainder = num % divider;
String prefix = String.valueOf(longNum);
if (remainder == 0L) {
return prefix + ".00";
} else {
double a = remainder;
double b = divider;
double temp = a / b;
// "-0.125"
String postfix = String.valueOf(temp);
log.warn("double <==> {}", temp);
if (postfix.contains("-") && postfix.length() > 4) {
if (postfix.charAt(4) >= '5') {
char t = postfix.charAt(3);
postfix = postfix.substring(0, 3);
int asciiChar = t - 0;
int intChar = (int) t;
char ch = (char) (t + 1);
log.error("减去整数0 <==> {} ,字符直接转整型 <==> {}", asciiChar, intChar);
return prefix + postfix + String.valueOf(ch);
}
}
if (postfix.contains("-") && postfix.length() <= 4) {
if (postfix.length() == 4) {
postfix = postfix.substring(1, 4);
return prefix + postfix;
}
if (postfix.length() == 3) {
postfix = postfix.substring(1, 3);
return prefix + postfix + "0";
}
}
if (!postfix.contains("-") && postfix.length() > 5) {
if (postfix.charAt(4) >= '5') {
// 0.126
int t = postfix.charAt(3);
postfix = postfix.substring(0, 3);
char ch = (char) ((char) t + 1);
return prefix + postfix + String.valueOf(ch);
}
} else {
if (postfix.length() == 4) {
postfix = postfix.substring(0, 4);
return prefix + postfix;
}
if (postfix.length() == 3) {
postfix = postfix.substring(0, 3);
return prefix + postfix + "0";
}
}
}
return "";
}
}