Form number for PHP value

Asked

Viewed 87 times

1

I have a variable with a string format value:

15000

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

How can I format the value?

Ex: variable with value of 124589 = 1245.89

  • 3

    Isn’t it just split by 100? https://ideone.com/quSxQ8

1 answer

5


Just divide by 100:

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

That will be a floating point number, but in case you need it, for whatever reason, let it be a string, just do the cast:

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

But, caring for, if his string is not numerical, depending on your PHP settings, the result may be unexpected:

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

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

  • If it is necessary to convert the value to numeric: $resultado = floatval("1234589" / 100); // 12345.89

  • 3

    @Rodrigotognin the result of the division will already be numerical, do not need to do the conversion.

  • Okay, so you can remove the (string), because you would be forcing the variable to string instead of numerical

  • 3

    @Rodrigotognin I think you skipped that part: "but if you need it, for whatever reason, let it be a string, just cast it:" (or maybe I don’t understand where you’re going)

  • @Bacco My intention was to force the number to float, because I did not know the simple fact of dividing a string by a number already returned float. My intention was to make sure that the result of the split would float. It was an innocence of mine.

  • 2

    @Rodrigotognin understood. PHP has an automatic type coercion (as you have already noticed). At this point he is less "crazy" than JS, which uses some kind of complex rules.

  • 2

    @Rodrigotognin For mathematical operators, PHP will treat operands as numerical. Behind the scenes, what happens is that the string is first evaluated as numerical and then divided, so that "10" / "2" will return int(5). The link I added at the end of the reply deals with this if you want to read more.

  • @Andersoncarloswoss Cool! I’ll take a look. Thank you

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.