在本文中,我們將了解MySQL ROUND()函數如何在PHP中工作。使用了MySQL ROUND()函數四舍五入到指定的小數位。如果沒有提供指定的小數位然後四舍五入將數字四舍五入到最接近的整數。
用法:
ROUND(X, D)
SELECT ROUND(column1), ... ROUND(column n) from TABLE;
在這裏,我們采用學生數據庫來執行round()操作。
要求:
- XAMPP服務器
PHP是一種服務器端腳本語言,可與MySQL進行通信以管理數據庫。的MySQL是一個開放源代碼關係數據庫管理係統(RDBMS)。 MySQL由Oracle Corporation開發,分發和支持。
數據庫表截圖:
MySQL查詢四舍五入到parent_salary:
SELECT parent_salary, ROUND(parent_salary) FROM student;
結果:
Parent salary:50000 — rounded to:50000
Parent salary:25000.8 — rounded to:25001
Parent salary:10001 — rounded to:10001
Parent salary:50000 — rounded to:50000
Parent salary:50000 — rounded to:50000
Parent salary:89000.1 — rounded to:89000
MySQL查詢四舍五入的學生成績:
SELECT name, ROUND(percentage) FROM student;
結果:
Student name:ojaswi — percentage:79
Student name:sravan kumar — percentage:98
Student name:bobby — percentage:80
Student name:ojaswi — percentage:79
Student name:rohith — percentage:89
Student name:gnanesh — percentage:69
方法:
- 啟動XAMPP服務器。
- 打開phpMyAdmin數據庫管理器並創建一個名為test的數據庫。
- 在測試數據庫中創建一個名為Student的表。
- 將學生的記錄插入表格中。要將數據插入表中,我們可以使用SQL查詢,也可以將數據直接插入表中。
- 編寫PHP代碼以執行MySQL round()函數並獲取四舍五入數據。
程序:
PHP
<?php
// Store the servername in a variable
$servername = "localhost";
// Store the username in a variable
$username = "root";
//Store the password in a variable
$password = "";
// Store the database name in a variable
$dbname = "test";
// Create connection by passing these
// connection parameters
$conn = new mysqli($servername,
$username, $password, $dbname);
echo "Parent Salary";
echo "<br><br>";
// SQL Query to select the data from
// database tablr
$sql = "SELECT parent_salary,
ROUND(parent_salary) FROM student";
$result = $conn->query($sql);
// Display data on the web page
while($row = mysqli_fetch_array($result)){
echo " Parent salary:" .
$row['parent_salary'] .
" => Round-off:" .
$row['ROUND(parent_salary)']
. "<br>";
}
echo "<br>*****************************";
echo "<br>Students Percentage";
echo "<br><br>";
// SQL Query to extract data from database
$sql = "SELECT name, ROUND(percentage) FROM student";
$result = $conn->query($sql);
// Display data on the web page
while($row = mysqli_fetch_array($result)){
echo " Student name :". $row['name'] .
" => Percentage:"
. $row['ROUND(percentage)'] . "<br>";
}
// Close the connection
$conn->close();
?>
輸出:
相關用法
- MySQL ROUND()用法及代碼示例
- PHP round( )用法及代碼示例
- p5.js round()用法及代碼示例
- d3.js band.round()用法及代碼示例
- SQL Server ROUND()用法及代碼示例
- JavaScript Math round()用法及代碼示例
- Lodash _.round()用法及代碼示例
注:本文由純淨天空篩選整理自sravankumar8128大神的英文原創作品 PHP MySQL ROUND() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。