将整数转换为 php 中的小数值

Converting a whole number to decimal value in php

我有一个 PHP 应用程序,它应该将货币值插入到 MariaDB 中,其 table 列设置为十进制 (10,2)

为了确保格式正确,我最初做了一个 echo 语句,以确保使用我认为应该是正确格式的结果....

number_format($待转换变量, 2, '.', '');

但是,当我分配格式转换时,我被告知(通过 mysqli 错误代码)十进制值不正确。我试过将小数位调整在 13、10 和 4 之间;唉,不开心。

如有任何想法,我们将不胜感激 t-i-a


include '../includes/dbt.php';
    
//make sure a residence tile was selected or send them back to /play/index.php
if (!isset($_GET['residence'])) {
    //code here
} else if (isset($_COOKIE['startingBal'])){
    session_start();
    setCookie("residence", $_GET['residence'], time() + 86400);
    $residence = $_COOKIE['residence'];
                
    $balance    = $_COOKIE['startingBal'];
    $newBal     = '';
                
    switch ($residence) {
    case 'option1':
        $newBal = $balance - 3200;
        break;                          
    case 'option2':
        $newBal = $balance - 3000;
        break;                          
    case 'option3':
        $newBal = $balance - 800;
        break;
    case 'option4':
        $newBal = $balance - 700;
        break;                          
    default:
        $balance;
    }
    $formattedNewBal    = number_format($newBal, '2','.','');
    $ingameStatsUpdate  =  "INSERT INTO ingameStats (`nickname`, `residence`, `newBal`) VALUES ('$nickname', '$residence', '$formattedNewBal')";
            
    if (mysqli_query($conn, $ingameStatsUpdate)) {
                
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
        
    //unset starting balance cookie since now the database will keep track of the balance moving forward
    setCookie("startingBal", "", time() -3600);
                    
    // close connection 
    mysqli_close($conn);
}
    

有两个问题。

首先,您没有正确设置 $residence。调用 setcookie() 不会更新 $_COOKIE 数组,因此 $residence = $_COOKIE['residence']; 不会将其设置为您刚刚分配的值。参见 Why are my cookies not setting?

其次,您的 default: 案例没有成立 $newBal。因此,如果 none 的情况匹配,$newBal 仍然有一个空字符串,这是 MySQL.

中的无效浮点值
    session_start();
    $residence = $_GET['residence'];
    setCookie("residence", $residence, time() + 86400);
                
    $balance    = $_COOKIE['startingBal'];
                
    switch ($residence) {
    case 'option1':
        $newBal = $balance - 3200;
        break;                          
    case 'option2':
        $newBal = $balance - 3000;
        break;                          
    case 'option3':
        $newBal = $balance - 800;
        break;
    case 'option4':
        $newBal = $balance - 700;
        break;                          
    default:
        $newBal = $balance;
    }