Repository navigation
Expand file tree
/
Copy pathfloating-point.php
More file actions
93 lines (80 loc) · 2.26 KB
/
Copy pathfloating-point.php
File metadata and controls
93 lines (80 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
class FloatingPoint
{
public function main()
{
$this->example1();
// $this->example2();
// $this->example3();
}
/**
* Difference is a small fraction
*/
private function example1()
{
$display_price = 50.39;
$shipping_price = 35.12;
$asking_price = 15.27;
// 0 = 15.27 - ( 50.39 - 35.12 )
$actual_seller_discount = $asking_price - ($display_price - $shipping_price);
$expected_seller_discount = 0.00;
if ($actual_seller_discount === $expected_seller_discount) {
$this->print_ra('Do something really important');
} else {
$this->print_ra('Houston, we have a problem...');
var_dump($actual_seller_discount);
var_dump($expected_seller_discount);
}
/**
* SPOILER ALERT
* $actual_seller_discount = bcadd($asking_price, -(bcadd($display_price, -$shipping_price, 2)), 2);
*/
}
/**
* Difference is hidden
*
* See: https://github.com/RecycledMedia/tradesy-common/blob/master/src/Tradesy/Purchase/Checkout.php#L873
*/
private function example2()
{
$asking_price = 8;
$discount = 6.4;
$actual_display_price = $asking_price - $discount;
$expected_display_price = 1.6;
if ($actual_display_price === $expected_display_price) {
$this->print_ra('Do something really important');
} else {
$this->print_ra('Houston, we have a problem...');
var_dump($actual_display_price);
var_dump($expected_display_price);
}
/**
* SPOILER ALERT
* ini_set("precision", 18);
*/
}
/**
* Same value is stored - 'precision' setting is just a more restrictive number formatter.
*/
private function example3()
{
$i = 8-6.4;
var_dump($i);
ini_set('precision', 17);
var_dump($i);
ini_set('precision', 24);
var_dump($i);
}
/**
* Pretty print
*
* @param $val
*/
private function print_ra($val)
{
print '<pre>';
print_r($val);
print '</pre>';
}
}
(new FloatingPoint())->main();