Norbert Mahalik
Norbert Mahalik

Reputation: 47

Float value from database doesnt display correctly php

Here is the code that displays a select box with database entries.

The problem is that values 1.2 and 1.3 in the database display as 1.2000000476837 and 1.2999999523163 even though the other float values display correctly.


I would appreciate any help.

<select name="capacity" tabindex="7">
                        <option value="">Odaberi kapacitet</option>
                        <?php
                        $query_select_capacity=$db->prepare("SELECT id_capacity, capacity FROM capacity");
                        $query_select_capacity->execute();
                        $result=$query_select_capacity->fetchAll(PDO::FETCH_ASSOC);
                        foreach($result as $res){
                                echo "<option value='".$res['id_capacity']."'>".$res['capacity']."&nbsp;&nbsp;</option>";
                        }
                        ?>
           </select>

Here is the database table.

CREATE TABLE IF NOT EXISTS `capacity` (
`id_capacity` int(11) NOT NULL AUTO_INCREMENT,
`capacity` float DEFAULT NULL,
 PRIMARY KEY (`id_capacity`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ; 

INSERT INTO `capacity` (`id_capacity`, `capacity`) VALUES
(1, NULL),
(6, 1.2),
(7, 1.3),
(8, 1.5),
(9, 2),
(10, 2.5);

Upvotes: 1

Views: 144

Answers (2)

chris
chris

Reputation: 125

Your problem is not your code it is the way your PC (and all other personal computers) saves float values. It saves the value not as 1.2, it saves it, in a simple way, the part before the '.' (in your case the 1) and then it saves the value behind the '.'

Hence, 1/2 + 1/4 + 1/8 +...

so 0.2 would be

  0*1/2 + 0*1/4 + 1*1/8(=0,125 so 0,75 are left) 
+ 1*1/16(=0,0625 so 0,0125 are left) + ... and so on

the number of 1/ are limited so you can never reach the perfect value 0.2 or 0.3

I hope this will help you a little bit.

Upvotes: 2

Julio Soares
Julio Soares

Reputation: 1190

It shows just fine for here

<select name="capacity" tabindex="7">
    <option value="">Odaberi kapacitet</option>
    <option value="1">&nbsp;&nbsp;</option>
    <option value="6">1.2&nbsp;&nbsp;</option>
    <option value="7">1.3&nbsp;&nbsp;</option>
    <option value="8">1.5&nbsp;&nbsp;</option>
    <option value="9">2&nbsp;&nbsp;</option>
    <option value="10">2.5&nbsp;&nbsp;</option>
</select>

Upvotes: 0

Related Questions