Form number for value in PHP

1

I have a variable with a value in string format:

15000

I need to compare this value with another value in the database. It turns out that in this string that comes with the value, the last two digits are always referring to the cents. That is, the above value is 150.00

How can I format the value?

Ex: variable with value of 124589 = 1245.89

    
asked by anonymous 17.08.2018 / 14:23

1 answer

5

Just divide by 100:

$resultado = "1234589" / 100;  // 12345.89

This will be a floating-point number, but if you need, for whatever reason, that this is a string , just do the cast :

$resultado = (string) ("1234589" / 100);  // "12345.89"

But care , if your string is not numeric, depending on your PHP settings, the result may be unexpected:

$resultado = "batatas" / 100;  // 0

Read more in Why in PHP is the expression "2 + '6 apples'" equal to 8?

    
17.08.2018 / 14:32