Number format for calculation

When 10000-100, the result should be 9900.

I tried when I used: -

< ?php $num1 = number_format(round(10000,1),2); $num2 = number_format(round(100,1),2); echo $num1 - $num2; ?> 

The above result is -90, which made me realize that the number_format function is not applicable in the calculations.

Is there any way to convert the value of number_format (obtained from POST from the previous page) back to a numerical value for normal calculation?

+4
source share
3 answers

To get started, the reason is that:

 (int) "10,000.00" 

allows 10 because it stops parsing at the first non-numeric character. Thanks to a weird PHP type system, this is done implicitly when you subtract lines.

Yes, you can easily break commas:

 $unformatted = str_replace(",", "", $formatted); 

but it only clears the message of the raw numeric value (you can use number_format for the displayed value).

EDIT: good practice for explicitly converting numeric strings (without commas) to float (or int) with cast ( (int) or (float) ) or function version ( intval or floatval ).

+5
source

I do not think that you can fulfill this 10,000.00 -100.00 with a comma in the equation. Just do the original arithmetic operation and then format the answer .

 $num1 = 10000; $num2 = 100; echo number_format(round($num1 - $num2,1),2); 

Displays

 9,900.00 
0
source

There is an easier way.

number_format is for outputting numbers or rounding prime numbers. number_format gives us the ability to make well-rounded rounded numbers for better user convenience. To calculate and store numbers in a MYSQL database, use this.

Save your numbers in MYSQL always as a DECIMAL type, not a FLOAT. There are many mistakes if you want to calculate the FLOAT fields.

Instead of using English notation.

 $number = 1234.56; // english notation without thousands separator $english_format_number = number_format($number, 2, '.', ''); // // 1234.57 

And now you can calculate and save it without errors. Always remember that storing numbers in $ var is always a string. Yes, you can use the deifine type, but in the first case it does not matter, and it can be explained here.

For more information on number_format see here โ†’ http://php.net/manual/en/function.number-format.php

0
source

All Articles