Sco*_*ott 5 java formatting scientific-notation decimal
我正在使用Java的DecimalFormat类在Scientific Notation中打印出数字.但是,我有一个问题.无论价值如何,我都需要字符串固定长度,并且十次幂的符号将其抛弃.目前,这是我的格式:
DecimalFormat format = new DecimalFormat("0.0E0");
Run Code Online (Sandbox Code Playgroud)
这给了我以下组合:1.0E1,1.0E-1,-1.0E1和-1.0E-1.
我可以使用setPositivePrefix获取:+ 1.0E1,+ 1.0E-1,-1.0E1和-1.0E-1,或者我喜欢的任何东西,但它不会影响权力的标志!
有没有办法做到这一点,以便我可以有固定长度的字符串?谢谢!
编辑:啊,所以使用Java现有的DecimalFormat API 无法做到这一点?谢谢你的建议!我想我可能必须继承DecimalFormat,因为我受限于已经存在的接口.
小智 6
这对我有效
DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.US);
if (value > 1 || value < -1) {
SYMBOLS.setExponentSeparator("e+");
} else {
SYMBOLS.setExponentSeparator("e");
}
DecimalFormat format = new DecimalFormat(sb.toString(), SYMBOLS);
Run Code Online (Sandbox Code Playgroud)
这是一种方法。也许很做作,但它确实有效……
public class DecimalFormatTest extends TestCase {
private static class MyFormat extends NumberFormat {
private final DecimalFormat decimal;
public MyFormat(String pattern) {
decimal = new DecimalFormat(pattern);
}
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
StringBuffer sb = new StringBuffer();
sb.append(modified(Math.abs(number) > 1.0, decimal.format(number, toAppendTo, pos).toString()));
return sb;
}
private String modified(boolean large, String s) {
return large ? s.replace("E", "E+") : s;
}
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
StringBuffer sb = new StringBuffer();
sb.append(modified(true, decimal.format(number, toAppendTo, pos).toString()));
return sb;
}
public Number parse(String source, ParsePosition parsePosition) {
return decimal.parse(source, parsePosition);
}
public void setPositivePrefix(String newValue) {
decimal.setPositivePrefix(newValue);
}
}
private MyFormat format;
protected void setUp() throws Exception {
format = new MyFormat("0.0E0");
format.setPositivePrefix("+");
}
public void testPositiveLargeNumber() throws Exception {
assertEquals("+1.0E+2", format.format(100.0));
}
public void testPositiveSmallNumber() throws Exception {
assertEquals("+1.0E-2", format.format(0.01));
}
public void testNegativeLargeNumber() throws Exception {
assertEquals("-1.0E+2", format.format(-100.0));
}
public void testNegativeSmallNumber() throws Exception {
assertEquals("-1.0E-2", format.format(-0.01));
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以子类化DecimalFormat,但我发现不从具体类子类化通常更干净。