Open In App

Node.js MySQL FORMAT() Function

Improve
Improve
Like Article
Like
Save
Share
Report

FORMAT() function is a built-in function in MySQL that is used to format input numbers in the format of …**, ***, *** also, round float numbers to a specific number of decimal places.

Syntax:

FORMAT(number, number_of_decimal_places)

Parameters: It takes two parameters as follows:

  • number: The number which is given for formatting.
  • number_of_decimal_places: It is the number of decimal places.

Return Value: It returns a formatted number as a String in the format of …**, ***, ***.

Module Installation: Install the mysql module using the following command:

npm install mysql

Database: Our SQL publishers table preview with sample data is shown below:

Example 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);
    });
});


Run the index.js file using the following command:

node index.js

Output:

Example 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);
    });
});


Run the index.js file using the following command:

node index.js

Output:



Last Updated : 17 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads