2017-06-01 21 views
-1

我運行一個wooocommerce網站,重量是磅,我需要將它們轉換爲千克。如何在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(); ?> 

回答

5

閱讀本refrence:

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); 
+0

THX,該訣竅 – huskerone

3

您需要的價值爲

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

分配給某個變量試試這個

相關問題