问题描述
我最近正在使用数字,我有一种情况,我希望将双精度值的精度设置为6位数或4位数,具体取决于数据库中存储的值。
I was working with numbers recently and I had a situation where I want to set the precision of a double value say to 6 digits or 4 digits, depending on the value stored in the database.
例如,如果在数据库中精度设置为4位,则输出必须为,
For example, If in the database the precision is set as 4 digits then the output must look as,
10.0000
。
我尝试使用 DecimalFormat
并使用字符串 ##。####
,但每次使用符号都很烦人。
I tried with DecimalFormat
and using the string ##.####
, but it is annoying to use symbols everytime.
有没有更好的方法,如下所示:
Is there any better approach, say something like below:
Double value = 10.0;
value.setPrecision(4);
推荐答案
您无法设置双精度(或Double)到指定的十进制数字,因为浮点值没有十进制数字。它们具有二进制数字。
You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.
您必须通过 BigDecimal
或<$ c转换为十进制基数$ c> DecimalFormat ,具体取决于您稍后要对该值执行的操作。
You will have to convert into a decimal radix, either via BigDecimal
or DecimalFormat
, depending on what you want to do with the value later.
另请参阅我对对于不可避免的反驳* 100/100答案。
See also my answer to this question for a refutation of the inevitable *100/100 answers.
这篇关于Java:如何为double值设置Precision?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!