Home > Blockchain >  How to Convert Number to always have 2 digits after the decimal?
How to Convert Number to always have 2 digits after the decimal?

Time:10-14

Quick question: I am trying to always get 2 digits after the money amount I previously had this code:

case 'tool_paid':
      echo get_post_meta ( $post_id, 'tool_paid', true );
      break;

But it only returns me 650 and I want it to return 650.00 I have tried the following with no success:

case 'tool_paid':
      $toolpaid = get_post_meta ( $post_id, 'tool_paid', true );
      echo $toolpaid number_format(2);
      break;

Thanks for any help on this, still a noob at php.

CodePudding user response:

You need

case 'tool_paid':
      $toolpaid = get_post_meta ( $post_id, 'tool_paid', true );
      echo number_format($toolpaid,2);  // Corrected syntax & parameters here.
      break;

PHP will coerce the variable to float as required, unless declare(strict_types=1), in which case it will fail with a TypeError. You can coerce the number if need be with simple cast.

For example:

echo number_format((float)$toolpaid,2);

The PHP manual is a good place to look for function parameters and syntax.

Demo:https://3v4l.org/MpFMi

  • Related