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?
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.
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.
The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.
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; }
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 }
(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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With