gpt4 book ai didi

java - 如何在没有科学计数法的情况下将String转换为BigDecimal

转载 作者:行者123 更新时间:2023-11-30 06:11:58 26 4
gpt4 key购买 nike

我正在尝试将 String 值转换为 BigDecimal 值。当我使用 0.000001234 时,我在 BigDecimal 中得到相同的值。但是,当我使用 0.000000123 或 0.000000012 时,我得到 1.23E-7 或 1.2E-8。

我需要如下,如果输入是 String = 0.000000123

那么输出应该是,BigDecimal = 0.000000123

请帮帮我

import java.math.BigDecimal;

public class DecimalEx {


public static void main(String args[]){

String s = "0.000000023";
BigDecimal big = new BigDecimal(s);
System.out.println(big);
}
}

最佳答案

您可以毫无问题地将 String 转换为 BigDecimalBigDecimal 值不知道该值是否具有指数符号...它只是一个缩放值。

您看到的问题是当您隐式调用 BigDecimal.toString() 时,据记载有时会使用指数表示法:

If the scale is greater than or equal to zero and the adjusted exponent is greater than or equal to -6, the number will be converted to a character form without using exponential notation.

相反,您想使用 BigDecimal.toPlainString() :

Returns a string representation of this BigDecimal without an exponent field.

只需将最后一行代码更改为:

System.out.println(big.toPlainString());

关于java - 如何在没有科学计数法的情况下将String转换为BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com