简体   繁体   English

如何在Java中为E表示法设置特定格式

[英]How to set specific format for E notation in Java

I need to convert some floats to format like this: 2,5000E-003 , 2,8625E+000我需要将一些浮点数转换为这样的格式: 2,5000E-003 , 2,8625E+000

I know i can do it like this:我知道我可以这样做:

String.format("%s,%sE%s", digitInt, digitAfterDot, digitDegree)

But I hope somebody knows more clever and natty solution但我希望有人知道更聪明和整洁的解决方案

You can use:您可以使用:

String.format("%1.4e",12345.67890123)

The result of this is:这样做的结果是:

1,2346e+04

Here is some documentation这是一些文档

EDIT编辑
If you need 3 digits in the exponent, you can use the DecimalFormat Formatter:如果指数中需要 3 位数字,则可以使用DecimalFormat Formatter:

DecimalFormat format = new DecimalFormat("0.0000E000");
System.out.print(format.format(12345.67890123f));

Which outputs:哪些输出:

1,2346E004

Note that it does not come with a positive sign if the exponent is positive.请注意,如果指数为正,则它不会带有正号。 You can fix this with:您可以通过以下方式解决此问题:

DecimalFormat format = new DecimalFormat("0.0000E000");
String result = format.format(12345.67890123f);
if (!result.contains("E-")) {
    result = result.replace("E", "E+");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM