Skip Navigation

[Resolved] php warning message when formatting currency field

This support ticket is created 5 years, 11 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 2 replies, has 2 voices.

Last updated by PaulS4783 5 years, 11 months ago.

Assisted by: Nigel.

Author
Posts
#1182024
php-warning.png

I am trying to format a custom field "price" for zero decimals and to use commas.

I created a custom shortcode:

// format numbers nicely with zero decimals and with commas
function format_my_number($atts) {
    $num = $atts["num"];
     
    return number_format($num, 0, '.', ',');
}
add_shortcode("format-currency", "format_my_number");

And used it like this in the content template:

 <h2>[format-currency num='[types field='price' output="raw" format='FIELD_VALUE'][/types]'] JPY</h2>

It seems to "work" but when I look at the template on the backend I can see a warning message:

Warning: number_format() expects parameter 1 to be float, string given in /home/mysite/public_html/wp-content/themes/astra-child/functions.php on line 31

The "price" custom field is a "number" so I am not sure why it says "string given" or shows this message.
Thoughts?

#1182117

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

All post meta is stored as a string in wp_postmeta. (Even arrays are serialised and stored as strings.)

Use floatval to convert the string to a floating number (which number_format expects).

See hidden link

#1187918

Thank you.
Function now works. As follows:

// format numbers nicely with zero decimals and with commas 
// function converts meta data which is stored as a string to a float
function format_my_number($atts) {
    $num = $atts["num"];
    $float_value_of_var = floatval($num);
     
    return number_format($float_value_of_var, 0, '.', ',');
}
add_shortcode("format-currency", "format_my_number");