如何在PHP中对数字进行舍入 [英] How to round a number in PHP

查看:47
本文介绍了如何在PHP中对数字进行舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经营一家电子商务网站,体重以磅为单位,我需要将其转换为公斤。

我从一个网站下载了这个脚本,它完成了工作,但它设置了带有很多小数的新权重,不确定如何对其进行舍入。

我试图使用round($new_weight, 2);,但它没有使用它,或者不确定将它放置在哪里或如何放置。

注意:我对php一无所知。此脚本是一个页面模板。它会在您打开它时进行更改。

<?php
/*
 *
 * Template name: wconvertor
 */
get_header();

$args = array( 'post_type' => 'product', 'posts_per_page' => 2500  );

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post(); 
global $product; 

$weight= get_post_meta( get_the_ID(), '_weight', true);

if ( ! empty( $weight ) ) {

    echo "id = ".get_the_ID(). " weight = ".$weight; 

    $new_weight = $weight / 2.2 ; 
    round($new_weight,2);

    echo "<br>new weight = ".$new_weight."  ********************";

    // id , key , value 
    $result = update_post_meta(get_the_ID(), '_weight', $new_weight);
    echo "result = ".$result;

}else{
    echo "<br>NO update for: ".get_the_ID();
}
endwhile; 
wp_reset_query(); 
?>
</div>

<?php get_footer(); ?>

推荐答案

阅读此参考:

http://php.net/manual/en/function.round.php

示例:

<?php
 echo round(1.95583, 2);  // 1.96
 echo round(5.045, 2);    // 5.05
 echo round(5.055, 2);    // 5.06
?>

将代码编辑为:

$new_weight = $weight / 2.2 ; 
$new_weight = round($new_weight,2);

这篇关于如何在PHP中对数字进行舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆