Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Unable to convert float to GMP

Tags:

php

I wanted to compare two float in PHP and because internal comparison is error prone I used GMP library but it gives me error on a simple comparison

if (gmp_cmp(0.2, 0.1) > 0) echo "First number is bigger";

The error is "gmp_cmp(): Unable to convert variable to GMP - wrong type"

like image 927
omidh Avatar asked Sep 10 '26 06:09

omidh


1 Answers

If you want to use GMP then try this:

a = "0.2";
b = "0.1";

a_s = explode(".", $a); // split on decimal point
b_s = explode(".", $b);

if (gmp_cmp(a_s[0], b_s[0]) > 0 || 
   (gmp_cmp(a_s[0], b_s[0]) == 0 && gmp_cmp(a_s[1], b_s[1]) > 0))

   echo "First number is bigger";

This will split a and b on the decimal point. If a is bigger than b (ignoring the decimal) then the first number is bigger. If the a and b are the same (ignoring the decimal) then we compare the decimal parts only to determine if a is bigger than b.

Hopefully that helps

like image 86
Chase Walden Avatar answered Sep 11 '26 20:09

Chase Walden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!