Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if number is decimal

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)

Any reliable way to do this?

like image 956
CodeVirtuoso Avatar asked Jul 21 '11 07:07

CodeVirtuoso


People also ask

How do you check whether a number is decimal or not?

function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place. '; else return 'It is a whole number.

How do you check if a number has a decimal in C?

The C library function int isdigit(int c) checks if the passed character is a decimal digit character. Decimal digits are (numbers) − 0 1 2 3 4 5 6 7 8 9.

How do you check if a number is a decimal in Python?

The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.


2 Answers

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; } 
like image 109
cwallenpoole Avatar answered Oct 02 '22 11:10

cwallenpoole


if you want "10.00" to return true check Night Owl's answer

If you want to know if the decimals has a value you can use this answer.

Works with all kind of types (int, float, string)

if(fmod($val, 1) !== 0.00){     // your code if its decimals has a value } else {     // your code if the decimals are .00, or is an integer } 

Examples:

(fmod(1.00,    1) !== 0.00)    // returns false (fmod(2,       1) !== 0.00)    // returns false (fmod(3.01,    1) !== 0.00)    // returns true (fmod(4.33333, 1) !== 0.00)    // returns true (fmod(5.00000, 1) !== 0.00)    // returns false (fmod('6.50',  1) !== 0.00)    // returns true 

Explanation:

fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))

Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)

From the PHP docs:

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator

like image 23
77120 Avatar answered Oct 02 '22 11:10

77120