Check If a Number Has a Decimal Place/Is a Whole Number

Check if a number has a decimal place/is a whole number

Using modulus will work:

num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5

Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:

'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5

How to check if a number has a decimal place/is a whole number?

You are interested in what is called the scale of your BigDecimal.

Call BigDecimal#scale.

BigDecimal x = new BigDecimal( "45.5343434" );
BigDecimal y = new BigDecimal( "45" );

x.scale(): 7

y.scale(): 0

You asked:

I would like to limit the decimal places by 4

Test for the scale being larger than four. If so, round.

    BigDecimal num = new BigDecimal(45);
if (num.scale() > 4) {
num = num.setScale(4, RoundingMode.HALF_UP);
}
System.out.println(num);

Output:

45

In case of more decimals:

    BigDecimal num = new BigDecimal("45.5343434");

45.5343

You can choose a different rounding mode to fit with your requirements.

How to check if a float value is a whole number

To check if a float value is a whole number, use the float.is_integer() method:

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

The method was added to the float type in Python 2.6.

Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:

>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0

which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:

>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996

You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:

>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648

If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:

>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True

For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:

def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

Whole number or decimal number

is_numeric will return true for floats too, considering floats are numeric

Finds whether the given variable is numeric. Numeric strings consist
of optional sign, any number of digits, optional decimal part and
optional exponential part. Thus +0123.45e6 is a valid numeric value.
Hexadecimal notation (0xFF) is allowed too but only without sign,
decimal and exponential part.

You can try is_float(), but if the input is a string it wont work.

var_dump( is_float( '23.5' ) ); // return false

So if you are dealing with something that is a string representation of a number then just look for a .

if ( strpos( $answer3, '.' ) === false )

You can add is_numeric if you need to

// Make sure its numeric and has no decimal point
if ( is_numeric( $answer3 ) && strpos( $answer3, '.' ) === false )

Check if a given number is a multiple of another number that is a decimal

It's a valid solution, but i'd suggest to use the modulus operator (%), like this:

const isValid = amount % 0.25 === 0;

How to determine if a decimal/double is an integer?

For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.

public static void Main (string[] args)
{
decimal d = 3.1M;
Console.WriteLine((d % 1) == 0);
d = 3.0M;
Console.WriteLine((d % 1) == 0);
}

Output:

False
True

Update: As @Adrian Lopez mentioned below, comparison with a small value epsilon will discard floating-point computation mis-calculations. Since the question is about double values, below will be a more floating-point calculation proof answer:

Math.Abs(d % 1) <= (Double.Epsilon * 100)

Check if number is decimal

You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

function is_decimal( $val )
{
return is_numeric( $val ) && floor( $val ) != $val;
}

check if number string contains decimal?

. means any char.
You have to quote the dot. "\."

Or you could test

if (result > Math.floor(result)) {
// not an decimal
}


Related Topics



Leave a reply



Submit