如何将小数添加到 php 函数输出中



我有自定义函数,可以汇总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>';
}

你需要使用WordPress number_format_i18n

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

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

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

在这里在线试用

$sum = 0; 
echo number_format($sum, 2, '.', ''); 

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

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

最新更新