Search code examples
phparraysfractions

different output of same value in different situations - array


I can't understand why these arrays give me different outputs:

• this value 1/4 came from a table (db)

id | value
...
2  | 1/4
3  | 1/7

echo $matrix[0][2]; //show 1/4

• but if i do = 1/4

echo $matrix[0][2] = 1/4 // show 0.25

this occurs in all fractions values. For example 1/7 in first example show 1/7, but in second show 0.142857142

So, my question is why ? I want always decimal value, but the first code as i said, is not working with decimals.

thanks


Solution

  • The value from the database is a string and the value you set yourself is a float.

    If you are using MySQL you can use mysql_fetch_field to know a field type, wich can be usefull when you're working with MyISAM (MySQL always return strings).

    You have the easy/ugly solution:

    $var = '1/4';
    echo (float)eval('return '.$var.';');
    

    An other solution:

    $var = '1/4';
    $tmp = explode('/', $var, 2);
    $tmp = $tmp[0]/$tmp[1];
    echo $tmp;
    

    But I think the best solution is to save the result in your database (0.25 for example) and to cast the results into float when you're getting them.