在java中具有特定精度的双重值 [英] Double value with specific precision in java

查看:82
本文介绍了在java中具有特定精度的双重值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编程一个简单的java程序。我需要从输入中获得一个字符串,并将其分为两部分:1-double 2-string。
然后我需要对double进行简单的计算,并将结果发送到具有特定精度的输出(4)。它工作正常,但输入为0时有问题,那么它不能正常工作。



例如对于这些输入,输出将是: p>

1公斤

输出:2.2046



3.1公斤

输出:6.8343



但当输入为0时,输出应为0.0000,但显示为0.0。
我该如何强制显示0.0000?



我阅读了关于双重精度的相似文章,他们建议像 BigDecimal class,但是我不能在这种情况下使用它们,
我的代码是这样做的:

 行= input.nextLine(); 
array = line.split();
value = Double.parseDouble(array [0]);
type = array [1];
value = value * 2.2046;
String s = String.format(%。4f,value);
value = Double.parseDouble(s);
System.out.print(value +kg\\\
);


解决方案

DecimalFormat 将允许您定义要显示的数位数。即使值为零,'0'将强制输出数字,而'#'将忽略零。



System.out .print(new DecimalFormat(#0.0000)。format(value)+kg\\\
);
应该是窍门。



请参阅文档



注意:如果频繁使用,出于性能原因,您应该仅将格式化程序实例化一次并存储参考: final DecimalFormat df = new DecimalFormat(#0.0000 ); 。然后使用 df.format(value)


I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string. Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.

For example for these input, output will be:

1 kg
output:2.2046

3.1 kg
output:6.8343

But when the input is 0, the output should be 0.0000, but it shows 0.0 . What should I do to force it to show 0.0000?

I read similar post about double precision, they suggest something like BigDecimal class, but I can't use them in this case, my code for doing this is:

line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");

解决方案

DecimalFormat will allow you to define how many digits you want to display. A '0' will force an output of digits even if the value is zero, whereas a '#' will omit zeros.

System.out.print(new DecimalFormat("#0.0000").format(value)+" kg\n"); should to the trick.

See the documentation

Note: if used frequently, for performance reasons you should instantiate the formatter only once and store the reference: final DecimalFormat df = new DecimalFormat("#0.0000");. Then use df.format(value).

这篇关于在java中具有特定精度的双重值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆