-1

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.

ShrockCo
  • 357
  • 1
  • 13
  • 1
    Does this answer your question? [Show a number to two decimal places](https://stackoverflow.com/questions/4483540/show-a-number-to-two-decimal-places) – MylesK Oct 14 '21 at 09:54

1 Answers1

1

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

  • Thanks but this throws me an error of `Fatal error: Uncaught TypeError: number_format() expects parameter 1 to be float, string given in C:\Users\...\wp-content\themes\custom-theme\custom\admincolumns.php on line 70` Also see code line [here](https://prnt.sc/1vx5gbw) – ShrockCo Oct 13 '21 at 01:16
  • Then something else is wrong. If you provide a number as a string (e.g. `"650"`) then PHP will coerce it as required. This works for all supported versions and at least as far back as PHP 5.6. See the demo I've linked to – Tangentially Perpendicular Oct 13 '21 at 01:34
  • Whoops, My dump show that number coming over as a string: `...theme\vendor\twig\twig\src\Extension\DebugExtension.php:61:string '650' (length=3)` what would I need to do to convert that? - Would you mind updating the code example? – ShrockCo Oct 13 '21 at 02:14
  • You might have `declare(strict_types=1)` set. I've update my answer and the demo. – Tangentially Perpendicular Oct 13 '21 at 02:22
  • That works: `echo number_format((float)$toolpaid,2);` ~Many thanks for all your help! – ShrockCo Oct 13 '21 at 02:45
  • @ShrockCo If this works for you, please accept the answer. Click the tick next to the answer. – Tangentially Perpendicular Oct 13 '21 at 02:50
  • One more question? If I decided to add a $ before the number such as $650.00 what would be the proper way to do this? – ShrockCo Oct 13 '21 at 02:52
  • You could just prepend the currency symbol with `'$'.number_format(...)`, or you could use `sprintf()` to format the number and add the symbol at the same time. There are other ways. – Tangentially Perpendicular Oct 13 '21 at 03:03