Java科学记数法
我正在解决我朋友给我的一个问题。我需要以 x.yzw*10^p
形式获取输入数字,其中 p
不为零,而 x.yzw
可以为零。我已经编写了程序,但问题是当我们有诸如 0.098
之类的数字时,十进制格式将使其变为 9.8
但我需要将其变为 9.800
,它必须始终输出为 x.yzw*10^p
。有人可以告诉我这是怎么可能的吗?
input: output:
1234.56 1.235 x 10^3
1.2 1.200
0.098 9.800 x 10^-2
代码:
import java.util.Scanner;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class ConvertScientificNotation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.###E0");
double input = sc.nextDouble();
StringBuffer sBuffer = new StringBuffer(Double.toString(input));
sBuffer.append("00");
System.out.println(sBuffer.toString());
StringBuffer sb = new StringBuffer(df.format(Double.parseDouble(sBuffer.toString())));
if (sb.charAt(sb.length()-1) == '0') {
System.out.println(sBuffer.toString());
} else {
sb.replace(sb.indexOf("E"), sb.indexOf("E")+1, "10^");
sb.insert(sb.indexOf("10"), " x ");
System.out.println(sb.toString());
}
}
}
I am working on a problem which was given to me by my friend. I need to take the input number in the form x.yzw*10^p
where p
is non zero and x.yzw
can be zeros. I have made the program but the problem is that when we have numbers such as 0.098
, decimal format will make it 9.8
but I need to get it to be 9.800
, it has to always be outputted as x.yzw*10^p
. can someone please show me how this is possible.
input: output:
1234.56 1.235 x 10^3
1.2 1.200
0.098 9.800 x 10^-2
Code:
import java.util.Scanner;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class ConvertScientificNotation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.###E0");
double input = sc.nextDouble();
StringBuffer sBuffer = new StringBuffer(Double.toString(input));
sBuffer.append("00");
System.out.println(sBuffer.toString());
StringBuffer sb = new StringBuffer(df.format(Double.parseDouble(sBuffer.toString())));
if (sb.charAt(sb.length()-1) == '0') {
System.out.println(sBuffer.toString());
} else {
sb.replace(sb.indexOf("E"), sb.indexOf("E")+1, "10^");
sb.insert(sb.indexOf("10"), " x ");
System.out.println(sb.toString());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么如果您想将“输出”转换为数字,请使用:
编辑
同时检查this 出来,它包含有关如何格式化数字的更多信息
then if you want to convert 'output' into a number, use:
EDIT
also check this out, it contains more information on how to format numbers
然后你可以搜索并替换 E:
Then you can just do a search and replace for E:
将格式字符串设置为“.000”,它不会从格式化的数字中删除“空”零。
make your format string ".000" and it will not drop 'empty' zeroes from your formatted number.