我试图弄清楚如何通过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/