0

我试图弄清楚如何通过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来输出一个数字?

4

5 回答 5

4

使用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());
于 2013-09-27T03:14:58.823 回答
1

通过 找到它String.indexOf('.')

public int findDecimalPlaces (String input) {
    int dot = input.indexOf('.');
    if (dot < 0)
        return 0;
    return input.length() - dot - 1;
}

您还可以通过setMinimumFractionDigits()setMaximumFractionDigits()设置输出格式来配置 DecimalFormat/NumberFormat,而不必将模式构建为字符串。

于 2013-09-27T02:59:10.777 回答
0
int sigFigs = decimal1.split("\\.")[1].length();

计算小数点右侧的字符串长度可能是实现目标的最简单方法。

于 2013-09-27T02:56:26.573 回答
0

如果你想要小数位,你首先不能使用浮点,因为 FP 没有它们:FP 有二进制位。BigDecimal,直接从“String.我不明白你为什么需要一个对象”中使用和构造它DecimalFormat

于 2013-09-27T03:57:11.523 回答
0

您可以使用正则表达式将数字字符串转换为格式字符串:

String format = num.replaceAll("^\\d*", "#").replaceAll("\\d", "0");

例如 "123.45" --> "#.00" 和 "123" --> "#"

然后将结果用作 DecimalFormat 的模式

它不仅有效,而且只有一条线。

于 2013-09-27T04:02:26.173 回答