【问题标题】:How to add decimals to php function output如何在php函数输出中添加小数
【发布时间】:2018-06-29 12:39:26
【问题描述】:

我有一个自定义函数,可以汇总 wordpress 数据库中自定义字段的值。

这些值已正确汇总并显示如下: 1500.3€

如何在小数点后添加一个尾随零,这样总和就会像这样显示 1500.30 欧元

我想我需要用 number_format() 格式化 $sum,但我不是 100% 确定如何在我的函数中使用 number_format。

它应该看起来像这样:

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

但是我可以将上述内容坚持到我的功能中吗?

自定义函数:

function kd_shortcode_group_progress($atts, $content = null) {
 extract( shortcode_atts( array(
    'challenge' => '0',
    'group' => '1',
), $atts ) );

global $wpdb;
$prefix = $wpdb->prefix;
global $kd_table;
$table = $prefix."postmeta";
$table2 = $prefix."posts";

$sum = 0;

$sql = "SELECT `post_id` FROM `".$table."` WHERE `meta_key` = 'wpcf-haaste_valmis' and `meta_value` = '".$challenge."';";
$people = $wpdb->get_results($sql);

$sql4 = "SELECT `id` as `post_id` FROM `".$table2."` WHERE `post_type` = 'osallistuja' and `post_title` = '".$group."';";
$ids = $wpdb->get_results($sql4);

$pageId = '';
foreach ($ids as $i => $id) {
    $people[] = $ids[$i];
}

foreach ($people as $i => $val) {
    $pid = $val->post_id;

    $sql2 = "SELECT `meta_value` as 'value' FROM `".$table."` WHERE `meta_key` = 'wpcf-keratty' AND `post_id` = '".$pid."';";
    $sql3 = "SELECT SUM(`price`) as 'value' FROM `".$kd_table."` WHERE `for` = '".$pid."';";

    $dons1 = $wpdb->get_results($sql2);
    $dons2 = $wpdb->get_results($sql3);

    foreach ($dons1 as $i2 => $val2) {
        $sum += $val2->value;
    }
    foreach ($dons2 as $i2 => $val3) {
        $sum += $val3->value;
    }   
}

return '<div class="groupDonations"><span style="color:#55A228!important;">This group has collected </span><br>'.$sum.'€</span></div>';
}

【问题讨论】:

  • 是的。正是这样。试一试有没有得到意想不到的结果?
  • 嗨!我确实尝试过: $sum = 0; number_format($sum, 2, '.', '');但它什么也没做。
  • 我没有意识到我必须这样写:$sum = 0; $sum = number_format($sum, 2, '.', '') 现在可以了。

标签: php wordpress numbers format decimal


【解决方案1】:

您需要使用WordPress number_format_i18n

$formatted = number_format_i18n( 1500.3, 2 ); // 1500.30

number_format 也可以,但它与语言无关

echo number_format(1500.3, 2, '.', ''); // 1500.30

Try it online here

【讨论】:

  • 嗨!我尝试了这两种方法并且都有效。我现在正在使用 number_format_i18n。我以前不知道 wordpress 有一个基于语言环境的数字格式化功能。谢谢!
【解决方案2】:
$sum = 0; 
echo number_format($sum, 2, '.', ''); 

工作正常 - 实际显示它可能是前端问题? 尝试将其用作字符串,

$sum = "" . number_format($sum, 2, '.', '');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2016-06-26
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多