Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string with decimals to number

So when I try the following:

$a = '1.00';
$b = '1.01';

if($a < $b){
    print 'ok';
}

This works fine. But when I retrieve these variables from an xml file. the strings are EXACTLY the same, but for some reason, the if function doesn't work right. So I assume I have to convert the strings to a number. But when I do so, the decimals get removed.

Is my assumption correct? If so, how do i solve it?

If not, what's the problem?

Thank you!

like image 656
Ilya Karnaukhov Avatar asked Jun 11 '12 12:06

Ilya Karnaukhov


People also ask

How do I convert a string to a number in PHP?

The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

What is Floatval PHP?

PHP | floatval() Function The floatval() function is an inbuilt function in PHP which returns the float value of a variable. Syntax: float floatval ( $var ) Parameters: This function accepts one parameter which is mandatory and described below: $var: The variable whose corresponding float value will be returned.

How check if string is integer PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.


1 Answers

$a = (float) $a;
$b = (float) $b;

Related reading: http://php.net/manual/en/language.types.type-juggling.php

like image 174
Geert Avatar answered Nov 15 '22 05:11

Geert