Java 通过将零添加为以下格式来转换用户的输入 XX.xxxxxx



我在 JavaScript 中完成了客户端验证,如果用户在小数点后输入一位数字或小数后输入少于 6 位数字,它会通过添加零来转换用户的输入值。例如:

  • 2.45 转换为 -> 02.450000
  • 数据输入 0(包括 0.0 或 0.00
  • 或 0.000 等(不是有效值

通过在 JavaScript 中使用下面的逻辑:

const formatInput = (input) => {
const [base, dec] = input.split('.');
let value = (!+base ? base : base.padStart(2, '0')) + '.' + (dec || '').padEnd(6, '0');
return value;
};
console.log(formatInput('2.45'))

现在我正在尝试在 JAVA 中实现相同的结果。如何在后端的 JAVA 中实现相同的逻辑?

我不知道我是否正确理解了你的问题,我也不明白为什么输入如此局限于这些特定数量的数字,但无论如何。我试图快速组合一个非常丑陋的解决方案,它根本没有优化。

我试图将输入限制为我理解您的描述的方式,并专注于构建您描述的输入。原来如此:

public static void main(String[] args) {
System.out.println(formatInput("0.060"));
System.out.println(formatInput("10.4960"));
System.out.println(formatInput("1.99"));
System.out.println(formatInput("9"));
System.out.println(formatInput("29.666666"));
System.out.println(formatInput("0.0"));
}
private static String formatInput(String input) {
String result = "";
String[] parts = input.split("\.");
StringBuilder sb = new StringBuilder();
if ((input == null) || (input.isEmpty()) || (!input.matches(".*[1-9].*")) || (parts.length < 1) || (parts.length > 2)
|| (parts[0].length() > 2) || (parts.length == 2 && parts[1].length() > 6)) { // filtering out the invalid cases
System.out.println("Invalid input.");
return result;
}
if (parts[0].length() == 1) {
sb.append('0');
}
sb.append(parts[0]).append('.');
if (parts.length == 2) { // input is of value xx.xx
sb.append(parts[1]);
for (int i = 0; i < 6 - parts[1].length(); i++) { // pad remaining zeroes
sb.append('0');
}
result = sb.toString();
} else if (parts.length == 1) { // input is of value x or xx
sb.append("000000");
result = sb.toString();
}
return result;
}

输出:

00.060000
10.496000
01.990000
09.000000
29.666666
Invalid input.

您可以使用 DecimalFormat 将输入值转换为所需的格式,然后将其存储到字符串中以保留格式。以下是示例代码片段

public void formatInput() {
double input = 2.45;
java.text.DecimalFormat df = new java.text.DecimalFormat("00.000000");
String formattedInput = String.valueOf(df.format(input));
System.out.println("Formatted text: " + formattedInput);
}

输出是

Formatted text: 02.450000

编辑1:如@saka1029所述,您可以使用String.format一次性使用。

最新更新