1

I'm trying to format a number in a table cell with comma separators between thousands. The number is coming from a custom field generated in Advanced Custom Fields plugin, where it is required to be a number.

(But I've also tried just entering the number directly in the below examples.)

I'm getting the correct number value, but the formatting isn't working. Plus, I get different results from number_format inside a table cell and outside one.

My number is 429000, retrieved by the_field('price').

Here's what I've tried inside the cell:

<td class="pl-property-price"><?php number_format( the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format((int) the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format( intval(the_field('price'))); ?> </td>
<td class="pl-property-price"><?php number_format( the_field('price'), 0, ".", ","); ?> </td>

and some other variations.

No matter what I do, it outputs 429000 without the comma separator.

Now, if I try to echo the value outside the table, using code like this and all the similar variations to the above using

<?php echo number_format(the_field('price')); ?>

I get 4290000 which adds an extra zero.

I'm puzzled.

  • How would like the number to look after formatting? – BenB Jun 25 '17 at 18:45
  • @batz I'm looking for 429,000 – user41091 Jun 25 '17 at 18:52
1

Seems like the function you using is the the_field function from of ACF which is a function that outputs a string so the formatting number_formatt dosent effect the output.

This code:

 <?php echo number_format(the_field('price')); ?>

The echo does not really print anything, the function the_fields prints the output, that's the reason the number_format function doesn't have any effect on the output.

Try getting the field via different function get_field for example, or you could add the the function the_fields a $format_value argument like you could see in the docs .

This should work:

<?php echo number_format( get_field( 'price' ) ); ?>
  • 1
    That's it. The echo is needed along with the use of get_field rather than the_field. I just discovered as well. Thanks for the help. – user41091 Jun 25 '17 at 19:24
0

In your case you need to use the get_field function instead of the_field.

the_field echos the value, whereas get_field returns a value in which you can pass as the parameter value to the number_format.

<?php echo number_format(get_field('price')); ?>

You can also learn more about number_format

0
  • get_field(): Returns the value of a specific field.
  • the_field(): Displays the value of a specific field.

The correct snippet looks like this:

<?php echo number_format( get_field( 'price' ) ); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.