库存产品计算和转换

时间:2017-11-22 03:05:23

标签: php floating-point decimal

我正在编制产品库存。现在我正在计算或将项目转换为更大的单元。

例如: 产品A:1盒= 12瓶

添加交易时,用户可以输入3盒和13瓶等数据。产品A的新值将为3 boxes and 13 bottles in storage。数据将保存到数据库tbl_transaction中。

如何自动转换/转换整个项目,例如4 boxes and 1 bottle in storage以添加到tbl_storage

我尝试过这个公式,但是当瓶子的数量在小数点时,我担心它不准确。

$bottles = 13;
$box = 12; 
$remaining_in_bottle = number_format($bottles / $box);// this will only convert the bottle into box (also tried float but not sure what I am doing)
$total_box = 3 + ???; 

echo $total_box." boxes and ".$remaining_in_bottle ." bottles in storage

2 个答案:

答案 0 :(得分:2)

我假设用户只输入数字作为boxesbottles的值,但如果不是,您只需要在执行以下计算之前从字符串中提取这些值:

代码:(Demo

$bottles_per_box=12; 

$user_input_bottles=13;
$user_input_boxes=3;

if($user_input_bottles>$bottles_per_box){
    // add truncated integer to box count.  DO NOT USE ROUND(), USE FLOOR()
    $user_input_boxes+=floor($user_input_bottles/$bottles_per_box);

    // store remainder after division
    $user_input_bottles=$user_input_bottles%$bottles_per_box;
    //                                     ^-- modulo operator
}

echo "New Bottles Total: $user_input_bottles\n";
echo "New Boxes Total: $user_input_boxes\n";

输出:

New Bottles Total: 1
New Boxes Total: 4

答案 1 :(得分:1)

我假设您要为tbl_transactiontbl_storage输入不同的内容。

<强> CODE

//Max bottle per box
$box_max_bottles = 12;

//User Input
$input_box = 3; 
$input_bottle = 13;

//Transaction
$transaction  = (($input_box > 1) ? $input_box . ' boxes' : $input_box . ' box') 
                . ' and ' . (($input_bottle > 1) ? $input_bottle. ' bottles' : $input_bottle. ' bottle'). ' in storage';

//Data will save into database tbl_transaction
echo $transaction;

//Get the remainder which is the remaining bottle
$total_bottle = $input_bottle % 12;

//Get the total boxes and divide the bottle into 12 
$total_box = floor($input_box + ($input_bottle / 12));

echo "<br />";

//Storage
$storage  = (($total_box > 1) ? $total_box . ' boxes' : $total_box . ' box') 
                . ' and ' . (($total_bottle > 1) ? $total_bottle . ' bottles' : $total_bottle . ' bottle'). ' in storage';

//Data will save into database tbl_storage
echo $storage;

<强>输出

交易

3 boxes and 13 bottles in storage

存储

4 boxes and 1 bottle in storage
相关问题