Java - 是否可以找出字符串的DecimalFormat

标签 java parsing decimalformat

我试图弄清楚如何通过String给定小数来计算有效数字的数量,以便我可以对小数进行计算并使用相同数量的打印结果有效数字。这是 SSCCE:

import java.text.DecimalFormat;
import java.text.ParseException;

public class Test {

    public static void main(String[] args) {
        try {
            DecimalFormat df = new DecimalFormat();
            String decimal1 = "54.60"; // Decimal is input as a string with a specific number of significant digits.
            double d = df.parse(decimal1).doubleValue();
            d = d * -1; // Multiply the decimal by -1 (this is why we parsed it, so we could do a calculatin).
            System.out.println(df.format(d)); // I need to print this with the same # of significant digits.
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

我知道DecimalFormat是1)告诉程序你打算如何显示你的小数(format())和2)告诉程序什么格式期望字符串表示的小数位于 (parse()) 中。但是,有没有办法从解析的字符串中推导出 DecimalFormat ,然后使用相同的 DecimalFormat 来输出数字?

最佳答案

使用BigDecimal :

        String decimal1 = "54.60"; 
        BigDecimal bigDecimal = new BigDecimal(decimal1);
        BigDecimal negative = bigDecimal.negate(); // negate keeps scale
        System.out.println(negative); 

或者简短版本:

        System.out.println((new BigDecimal(decimal1)).negate());

关于Java - 是否可以找出字符串的DecimalFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041947/

相关文章:

JavaScript promise 以相反的顺序加载

java - 使用正确的小数位格式化数字

java - Windows 8 64 位上的 Android Studio 找不到 JVD

java - Spring 警告 : Request method 'HEAD' not supported

java - JarSigner 在 java 中完成?

ruby-on-rails - 在处理电子邮件回复时,我怎样才能忽略任何电子邮件客户端细节和历史记录?

java - JAXB 如何创建具有不同属性值的重复元素

c - 在 C 中标记 s-表达式

java - 如何将十进制值格式化为小时和分钟?

Java DecimalFormatter - Locale DE 和 Locale US 之间的不同行为