Node.js MySQL FORMAT()函数
FORMAT()函数是 MySQL 中的一个内置函数,用于将输入数字格式化为…**、***、***的格式,还可以将浮点数舍入到特定的小数位数。
句法:
FORMAT(number, number_of_decimal_places)
参数:它需要两个参数,如下所示:
- number:用于格式化的数字。
- number_of_decimal_places:小数位数。
返回值:它以…**、***、***的格式将格式化的数字作为字符串返回。
模块安装:使用以下命令安装mysql模块:
npm install mysql
数据库:我们的 SQL发布者 带有示例数据的表格预览如下所示:
示例 1:
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query = "SELECT FORMAT(12345678.12555, 2) AS output";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query =
"SELECT FORMAT(salary, 1) AS formatted_salary FROM publishers";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出:
示例 2:
index.js
const mysql = require("mysql");
let db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'gfg_db'
});
db_con.connect((err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("We are connected to gfg_db database");
// Here is the query
let query =
"SELECT FORMAT(salary, 1) AS formatted_salary FROM publishers";
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出: