将小数转换为文本并在 Java 中再次转换回来

Convert decimal to text & back again in Java

我一直在尝试将文本转换为十进制但失败了,我搜索但没有得到 java 的结果,文本可以转换为二进制然后再转换为十进制,但我想直接转换并再次转换回来,请帮帮我。

我猜您有一个字符串格式的十进制数,想将其转换为十进制格式并返回。您是否尝试过以下操作:

String decimalAsString = "100.99";
double decimalAsDouble = Double.parseDouble(decimalAsString);
System.out.println("Decimal as Double: " + decimalAsDouble);

String decimalToStringAgain = Double.toString(decimalAsDouble);
System.out.println("Decimal as String: " + decimalToStringAgain);

不确定您是不是要将字符串的数据类型更改为双精度,例如。如果你有一个字符串“6.23”并且想要转换双精度“6.23”的数据类型。你可以使用 parseDouble() 方法。

public class StringToDecimal {
public static void main(String[] args) {
    String stringNum = "6.23";
    double decimalNum;

    decimalNum = Double.parseDouble(stringNum);

    System.out.println(decimalNum);
}
}

好吧,现在有了其他答案(即使问题中没有表现出任何努力),感觉必须提供一些替代方案:A BigDecimal

参见以下示例:

public static void main(String[] args) {
    // provide a decimal as text
    String decimalText = "512.56";
    // use it directly in the constructor of a BigDecimal
    BigDecimal bigDecimal = new BigDecimal(decimalText);
    // and receive the double value of that BigDecimal
    double decimal = bigDecimal.doubleValue();
    // then output some representations of the objects resp. primitives
    System.out.println(
            String.format("Text: %s, BigDecimal.toPlainString(): %s, double: %f",
                        decimalText, bigDecimal.toPlainString(), decimal)
    );
}

输出

Text: 512.56, BigDecimal.toPlainString(): 512.56, double: 512,560000