我如何确保十进制中有一定数量的数字(尾随零)
Posted
技术标签:
【中文标题】我如何确保十进制中有一定数量的数字(尾随零)【英文标题】:How can i make sure there is a certain amount of numbers in a decimal (trailing zeros) 【发布时间】:2018-01-06 00:40:01 【问题描述】:在我的网站上,有金额被回显。当我从金额中减去时,它会删除尾随的零,直到我注销并重新登录我的帐户。有没有办法检查小数点后是否总是有两个数字,如果没有则添加零?
这是我的php减法代码:
<?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();
?>
这是我的 php 回显代码:
<?php echo '$'.$cash_amount ?>
文档开头:
$cash_amount = $_SESSION['cash_amount'];
所以如果你能帮助我,我将非常非常感激。谢谢大家!
【问题讨论】:
试试sprintf
或str_pad
。
【参考方案1】:
试试
echo sprintf('%0.2f', $cash_amount);
或者在你的html/php中:
...
$<?php echo sprintf('%0.2f', $cash_amount) ?>
...
【讨论】:
完美!非常感谢!以上是关于我如何确保十进制中有一定数量的数字(尾随零)的主要内容,如果未能解决你的问题,请参考以下文章
在 SQL Server 中划分小数类型会导致不必要的尾随零