当前做一项目,涉及到的问题是从数据库中查询出来的数据为(String)
0.0
-0.07405
2001
如何转换为如下格式
0.000000E+00
-7.405000E-02
1.258650E+09
没看仔细,现在重新开始
[code="java"]
DecimalFormat f = new DecimalFormat("0.000000E00"); //定义格式
String str=f.format(Double.parseDouble("0.0"));
if (!str.contains("E-")) { //处理数据,给正数的科学计数法添加正号
str = str.replace("E", "E+");
}
System.out.println(str);
[/code]
我们可以单独定义一个方法:
[code="java"]
public static String transform(String str){
if (!str.contains("E-")) {
str = str.replace("E", "E+");
}
return str;
}
[/code]
这样大体过程如下:
[code="java"]
DecimalFormat f = new DecimalFormat("0.000000E00");
String str=f.format(Double.parseDouble("0.0"));
System.out.println(transform(str));
[/code]
运行结果是
0.000000E+00
-7.405000E-02
2.001000E+03
应该能满足你的要求
强制转换层long型不就行了嘛?
使用String类的
public static String format(String format, Object... args)方法,'g', 'G' 格式符根据精度和舍入运算后的值,使用计算机科学记数形式或十进制格式对结果进行格式化
刚才的方法并不能总是以科学计数法显示,得用java.text包中的DecimalFormat类,给你一段代码你看一下
[code="java"]
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
public static void main(String args[]) {
NumberFormat formatter = new DecimalFormat();
int maxinteger = Integer.MAX_VALUE;
System.out.println(maxinteger);
formatter = new DecimalFormat("0.######E0");
System.out.println(formatter.format(maxinteger));
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(maxinteger));
int mininteger = Integer.MIN_VALUE;
System.out.println(mininteger);
formatter = new DecimalFormat("0.######E0");
System.out.println(formatter.format(mininteger));
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(mininteger));
double d = 0.12345;
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(d));
formatter = new DecimalFormat("000000E0");
System.out.println(formatter.format(d));
}
}
[/code]
你可以参照java api,还有很多选项能定制
DecimalFormat f = new DecimalFormat("0.000000E00");
System.out.println(f.format(Double.parseDouble("0.0")));
System.out.println(f.format(Double.parseDouble("-0.07405")));
System.out.println(f.format(Double.parseDouble("2001")));
[color=red]结果是
0.000000E00
-7.405000E-02
2.001000E03
并不是
0.000000E+00 [/color]
科学计数法没有统一的标准,0.000000E+00是excel的格式吧,
可能java就把0.000000E00当成标准了呢,那个加号很重要吗,如果那样,你就自己处理下加号