📜  Java中的 BigDecimal toPlainString() 方法及示例

📅  最后修改于: 2022-05-13 01:54:56.400000             🧑  作者: Mango

Java中的 BigDecimal toPlainString() 方法及示例

Java.math.BigDecimal .toPlainString()方法用于表示当前的 BigDecimal,通过该方法将该方法调用为不带指数字段的字符串形式。如果数值为正比例,则小数点右侧的位数用于表示比例。对于具有零刻度或负刻度的值,生成结果字符串就好像该值已转换为具有零刻度的数值相等的值,并且好像零刻度值的所有尾随零都存在于结果中。
注意:如果将此方法的结果传递给字符串构造函数,则只会恢复此 BigDecimal 的数值,新的 BigDecimal 的表示可能有不同的比例。特别是,此方法的行为类似于 toString 方法。

句法:

public String toPlainString()

参数:此方法不接受任何参数。

返回值:此方法返回此 BigDecimal 数字的字符串表示形式,不带指数字段。

下面的程序说明了在Java中 toPlainString() 方法的使用

示例 1:将 BigDecimal 转换为没有指数表示法的纯字符串的示例

// Java program to demonstrate
// toPlainString() method of BigDecimal
  
import java.math.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating a BigDecimal object
        BigDecimal b;
  
        // Object of String to hold the number
        String input = "012345678901234567"
                       + "8901234567890123"
                       + "4567890123456789"
                       + "0123456789012345"
                       + "6789012345678901"
                       + "2345678901234567"
                       + "8901234567890123"
                       + "4567890123456789"
                       + "0123456789012345"
                       + "6789012345678901"
                       + "2345678901234567"
                       + "8901234567890123"
                       + "4567890123456789"
                       + "0123456789012345"
                       + "6789012345678901"
                       + "2345678901234567"
                       + "8901234567890123"
                       + "4554324324362432"
                       + "7674637264783264"
                       + "7832678463726478"
                       + "3264736274673864"
                       + "7364732463546354"
                       + "6354632564532645"
                       + "6325463546536453"
                       + "6546325463546534"
                       + "6325465345326456"
                       + "4635463263453264"
                       + "654632498739473";
  
        // Converting to BigDecimal
        b = new BigDecimal(input);
  
        // Apply toPlainString() method
        String s = b.toPlainString();
  
        // Print the result
        System.out.println(s);
    }
}
输出:

示例 2:使用指数表示法将 BigDecimal 转换为纯字符串的示例

// Java program to demonstrate
// toPlainString() method of BigDecimal
  
import java.math.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Create a BigDecimal object
        BigDecimal a;
  
        // Create a String object
        String s;
  
        a = new BigDecimal("4536785E10");
  
        // apply toPlainString() method
        s = a.toPlainString();
  
        // print the result
        System.out.println(s);
    }
}
输出:

参考资料: https: Java/javase/12/docs/api/ Java.base/ Java/math/BigDecimal.html#toPlainString()