检查数字是双精度还是整数 [英] Check if a number is a double or an int
问题描述
我试图通过显示1.2(如果是1.2)和1(如果是1)来美化程序,因为问题是我将数字存储为double值.如何检查数字是双精度还是整数?
I am trying to beautify a program by displaying 1.2 if it is 1.2 and 1 if it is 1 problem is I have stored the numbers into the arraylist as doubles. How can I check if a Number is a double or int?
推荐答案
好,您可以使用:
if (x == Math.floor(x))
甚至:
if (x == (long) x) // Performs truncation in the conversion
如果条件为true,即执行if
语句的主体,则该值为整数.否则,不是.
If the condition is true, i.e. the body of the if
statement executes, then the value is an integer. Otherwise, it's not.
请注意,这会将1.00000000001视为双精度-如果这些值是已计算(因此可能与整数值非常接近"),则可能需要增加一些公差.还要注意,对于非常大的整数,这将开始失败,因为无论如何它们都不能精确地表示在double
中-如果要处理的范围很广,则可能要考虑使用BigDecimal
.
Note that this will view 1.00000000001 as still a double - if these are values which have been computed (and so may just be "very close" to integer values) you may want to add some tolerance. Also note that this will start failing for very large integers, as they can't be exactly represented in double
anyway - you may want to consider using BigDecimal
instead if you're dealing with a very wide range.
有更好的方法来解决这个问题-使用DecimalFormat
您应该能够使它仅可选地产生小数点.例如:
There are better ways of approaching this - using DecimalFormat
you should be able to get it to only optionally produce the decimal point. For example:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("0.###");
double[] values = { 1.0, 3.5, 123.4567, 10.0 };
for (double value : values)
{
System.out.println(df.format(value));
}
}
}
输出:
1
3.5
123.457
10
这篇关于检查数字是双精度还是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!