我想弄清楚如何通過給定一個小數String
計算有效位數以便我可以對小數進行計算並打印出結果具有相同的有效位數。下面是一個SSCCE:Java - 是否有可能找出一個字符串的DecimalFormat
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
來輸出一個數字?
這是一個很好的解決方案。最有用,最準確,最簡單。更不要說'negate()'保持原始尺度的事實,它似乎是在構建'BigDecimal'時有人想到這個問題。 – ryvantage