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