【问题标题】:Number formatting incorrectly in PHP [duplicate]PHP中的数字格式不正确[重复]
【发布时间】:2017-05-13 18:43:35
【问题描述】:

我正在尝试在我没有创建的 Wordpress 主题中修改一些 PHP,并且开发人员不是很有帮助。

我正在为客户创建一个网站,以显示多个房产列表及其相关价格。当我在编辑器中输入数字时,它会删除所有小数。因此,如果我输入 16.50,它会立即变成 1650。我希望它能够显示 2 位小数。我已经做了一些研究,但我对 PHP 的了解不够,无法理解。开发人员指示我调整 $price_meta 的以下代码,但只需在数字上添加 2 个小数即可显示 1650.00。似乎小数在输入后立即被剥离。我还需要做些什么才能让它正确显示吗?

if(!function_exists('ct_listing_price')) {
function ct_listing_price() {
    global $post;
    global $ct_options;

    $ct_currency_placement = $ct_options['ct_currency_placement'];

    $price_prefix = get_post_meta(get_the_ID(), '_ct_price_prefix', true);
    $price_postfix = get_post_meta(get_the_ID(), '_ct_price_postfix', true);

    $price_meta = get_post_meta(get_the_ID(), '_ct_price', true);
    $price_meta= preg_replace('/[\$,]/', '', $price_meta);

    if($ct_currency_placement == 'after') {
        if(!empty($price_prefix)) {
            echo "<span class='listing-price-prefix'>";
                echo esc_html($price_prefix) . ' ';
            echo '</span>';
        }
        if(!empty($price_meta)) {
            echo "<span class='listing-price'>";
                echo number_format($price_meta, 2);
                ct_currency();
            echo '</span>';
        }
        if(!empty($price_postfix)) {
            echo "<span class='listing-price-postfix'>";
                echo  ' ' . esc_html($price_postfix) . ' ';
            echo '</span>';
        }
    } else {
        if(!empty($price_prefix)) {
            echo esc_html($price_prefix) . ' ';
        }
        if(!empty($price_meta)) {
            echo "<span class='listing-price'>";
                ct_currency();
                echo number_format($price_meta, 2);
            echo '</span>';
        }
        if(!empty($price_postfix)) {
            echo  ' ' . esc_html($price_postfix);
        }
    }
}

我对 PHP 的了解非常有限,所以如果您知道如何提供帮助,请尽可能用简单和规范的术语进行解释。

【问题讨论】:

  • 我尝试了这个解决方案,但我只能返回 1650.00 而不是 16.50。

标签: php wordpress number-formatting


【解决方案1】:

试试 number_format($price_meta, 2, '.', '');这应该输出 16.50

【讨论】:

    【解决方案2】:

    根据国际格式,可能有两种选择。

    如果您使用, 作为小数分隔符,则函数为:

    number_format($price_meta, 2, ',', '');

    如果您要求千位分隔符为 .,您只需将其添加到之前的函数中,如下所示:

    number_format($price_meta, 2, ',', '.');

    现在,另一方面,如果您需要使用. 作为小数分隔符,则必须进行切换:

    number_format($price_meta, 2, '.', '');

    并使用, 使用千位分隔符

    number_format($price_meta, 2, '.', ',');

    【讨论】:

    • 谢谢,但是我尝试了这个解决方案,但我只能返回 1650.00 而不是 16.50。
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多