Home > Mobile >  PHP Retain all decimals when using abs function
PHP Retain all decimals when using abs function

Time:07-20

I'm using the abs function to get the positive value of a negative number as follows:

$totalTax = -4.50 ;
echo abs($totalTax);

which is working well except it is dropping the 0 and returns 4.5 instead of 4.50.

Not sure why it's doing this or what the best method to retain all digits when using the abs function to convert a negative number to a positive? I need the 2 decimals regardless if the cents value is 0 for importing into an accounting system which only accepts 2 decimals and not 1.

CodePudding user response:

It's just because how PHP outputs leading/trailing zeros - trims them. Because there is infinite number of zeros after last non-zero number

e.g. echo 00000.1000000 will output 0.1

You should format your number to keep that leading and trailing zeros.

echo number_format($totalTax, 2, '.', '');
// -> 4.50

CodePudding user response:

You can try with the number_format() function. There is no possibility to retain trailing 0 with using only the abs() function.

Here is code you try:

$totalTax = -4.50 ;
$total_sub = abs($totalTax);  
echo number_format($total_sub, 2);
  •  Tags:  
  • php
  • Related