有没有更好的方法将数字转换为 Java 中具有可变小数精度的填充字符串?

Is there a better way to convert a number to a padded string in Java with a variable decimal precision?

我已经搜索过,但找不到答案。

无论如何,我需要将一个字符串(由数字转换而来)转换为另一个带小数点的字符串"assumed"。而且这个小数精度需要可变。

例如,假设我的伪方法是:

private String getPaddedNumber(String number, Integer decimalPlaces)...

因此用户可以:

 getPaddedNumber("200", 0);      //   "200"
 getPaddedNumber("200.4", 2);    //   "20040"
 getPaddedNumber("200.4", 1);    //   "2004"
 getPaddedNumber("200.4", 4);    //   "2004000"
 getPaddedNumber("200.", 0);     //   "200"  this is technically incorrect but we may get values like that.

现在,我实际上已经编写了一个可以执行所有这些操作的方法,但它非常强大。然后我想知道,“Java 是否已经有一个 DecimalFormat 或已经这样做的东西?

谢谢。

编辑

这些数字不会以科学记数法的形式出现。

一些数字示例:

"55"
"78.9"
"9444.933"

结果不会有小数点。

更多示例:

getPaddedNumber("98.6", 2);    //  "9860"
getPaddedNumber("42", 0);      //  "42"
getPaddedNumber("556.7", 5);   //  "55670000"

EDIT2

这是我目前使用的代码。它并不漂亮,但它似乎在工作。但我不禁觉得我重新发明了轮子。 Java 是否有原生的东西可以做到这一点?

private static String getPaddedNumber(String number, int decimalPlaces) {

    if (number == null) return "";
    if (decimalPlaces < 0) decimalPlaces = 0;

    String working = "";
    boolean hasDecimal = number.contains(".");

    if (hasDecimal) {
        String[] split = number.split("\.");
        String left = split[0];
        String right;

        if (split.length > 1)
            right = split[1];
        else
            right = "0";

        for (int c = 0; c < decimalPlaces - right.length(); c++)
            working += "0";

        return left + right + working;
    }

    for (int c = 0; c < decimalPlaces; c++)
        working += "0";

    return number + working;
}

您可以使用BigDecimal class将scientific notation转换为可用的数字:

String test = "200.4E2";
int val = new BigDecimal(test).intValue();
double val1 = new BigDecimal(test).doubleValue();
System.out.println("" + val);

等...

****更新*****

public static void main(String[] args) throws FileNotFoundException {
    String test = "200.4E2";
    String test2 = "200E0";
    String val = new BigDecimal(test).toPlainString();
    String val1 = new BigDecimal(test2).toPlainString();
    System.out.println("" + val);
    System.out.println("" + val1);
}

您可以将您的数字连接在一起以获得科学记数法:

String test = "200.4" + "E" + 2;

完整方法

private static String getPaddedNumber(String number, int decimalPlaces) {
    String temp = number + "E" + decimalPlaces;
    return new BigDecimal(temp).toPlainString();
}

代码取自here

类似于number * Math.pow(10, decimalPlaces)