开发者

PHP simplexml -- formatting integers

I'm using simplexml to recover xml from a remote server, and I get values that can look something l开发者_C百科ike this:

1.28586732

-1.2357956

I save these values in a variable but I would like to:

  1. Display each value with no more than 2 decimal places
  2. Have a plus sign precede the value if it is positive
  3. Apply different CSS styles depending on whether the value is positive or negative (for instance display value in red if it is negative)

Thanks!


To display only 2 decimal places you can either use round($num, 2) or sprintf("%.2f", $num), the difference is that sprintf always returns 2 decimal places, i.e. 5 would be 5.00, while round only shows the necessary amount of decimal places. sprintf is also locale-aware.

To have a plus sign precede the value, you would simply do if ($num >= 0) $num = '+'.$num;

And finally to do CSS styling, you should wrap the number in a span and give it a class, i.e. either positive or negative.

To do all of the three, you could have a function like this:

function format_decimal($num)
{
    return sprintf(
        '<span class="%s">%+.2f</span>',
        $num < 0 ? 'negative' : 'positive',
        $num
    );
}


let:

$s=1.2344545665

if($s>=0)
{
echo "<div class=\"addclass\">+".roundDigits($s,2) . "</div>";
}
else
{
echo "<div class=\"minusclass\">-".roundDigits($s,2) . "</div>";
}


Check out number_format. http://php.net/manual/en/function.number-format.php Then if >= 0 for a positive, <= negative checks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜