Reputation: 592
I have this Custom Posts with several number fields in it, i'm looking forward to format the numbers given(in the edit post in the backend for the admin) immediatly after presented, in a money format, that means, the number field should accept commas too. I'm not sure on how to start, have any of you done something similiar?
Please help I'm kinda new to wordpress
Upvotes: 0
Views: 4500
Reputation: 96
Have a look at number_format.
Here's an example of dealing with numeric and non-numeric values. Uncomment //$unformatted = "13,009";
to see the string version in action.
Hopefully this is all enough to point you in the right direction.
// Different versions of a number
$unformatted = "13009";
//$unformatted = "13,009";
// If the variable is a number
if (is_numeric ( $unformatted ) )
{
$formatted = number_format($unformatted); // Apply number format
$formattedDecimals = number_format($unformatted, 2); // Apply number format (with decimals)
echo $formatted."<br />".$formattedDecimals; // Output the values
}
// If the variable is text
else
{
$integerValue = str_replace(",", "", $unformatted); // Remove commas from string
$integerValue = intval($integerValue); // Convert from string to integer
$integerValue = number_format($integerValue); // Apply number format
$floatValue = str_replace(",", "", $unformatted); // Remove commas from string
$floatValue = floatval($floatValue); // Convert from string to float
$floatValue = number_format($floatValue, 2); // Apply number format
echo $integerValue."<br />".$floatValue; // Output values
}
Upvotes: 3