PHP price to int is losing a cent

<>

This question already has an answer here:

Answers


FuzzyTree's answer explained the problem with floating point arithmetic. You can fix it by using round before intval.

<?php
$val = 568.3 * 100;
echo $val;
echo "\n";
echo (float) ($val);
echo "\n";
echo (int) (round($val));
echo "\n";
echo intval(round($val));
echo "\n";
?>

Output:

56830
56830
56830
56830

$val is float with a value of something like 56829.999999... and it gets rounded down when converting to an int.

From the manual

http://www.php.net/manual/en/language.types.integer.php

From floating point numbers ΒΆ

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms other than Windows), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!


Need Your Help

Jquery, ajax: Clicking on a button and getting the value of the cell next to it on the same row

javascript jquery laravel

I have been reading the tutorials on JS and it occurred to me that I wanted the following:

QPushButton show/hide based on Mouse over event

c++ qt qt4 qt-creator

I have one question regarding the QPushButton.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.