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

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

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

Java.math.BigDecimal .toEngineeringString()方法用于表示当前 BigDecimal,如果需要指数,则使用工程符号将此方法调用为 String 形式。 BigDecimal 的字符串表示与 toString() 方法中描述的相同,不同之处在于如果使用指数表示法,则将 10 的幂调整为 3 的倍数(工程表示法),使得非零值的整数部分将在 1 到 999 的范围内。
句法:

public String toEngineeringString()

参数:此方法不接受任何参数。
返回值:此方法返回此 BigDecimal 数字的工程字符串表示形式。

下面的程序说明了在Java中 toEngineeringString() 方法的使用
示例 1:将 BigDecimal 转换为不带指数表示法的工程字符串的示例

// Java program to demonstrate
// toEngineeringString() 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"
                       + "4635463263453264"
                       + "654632498739473";
  
        // Converting to BigDecimal
        b = new BigDecimal(input);
  
        // Apply toEngineeringString() method
        String s = b.toEngineeringString();
  
        // Print the result
        System.out.println(s);
    }
}
输出:

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

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

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