In my website, there are money amounts being echoed. When I subtract from the money amounts, it removes the trailing zero until I log out and log back into my account. Is there a way to check that there are always two numbers after the decimal and add a zero if there isn't?
Here is my php subtraction code:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "patrick2002";
$dbname = "accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] -= 0.05;
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);
if($result)
{
echo "5 cents has been subtracted!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
And here is my php echo code:
<?php echo '$'.$cash_amount ?>
At the beginning of the document:
$cash_amount = $_SESSION['cash_amount'];
So if you could help me, I'd be very very grateful. Thanks guys!
try
echo sprintf('%0.2f', $cash_amount);
Or in you html/php:
...
$<?php echo sprintf('%0.2f', $cash_amount) ?>
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.