Converting a Numeric Value to a Formatted String in Javascript

JavaScript offers multiple ways to convert a numeric value to a formatted string, each with its own advantages and use cases.

Concatenating an empty string:

 
let number = 123;
let stringNumber = '' + number;
console.log(stringNumber); // Output: "123"
 
 

Explanation: By concatenating an empty string ('') with the number, JavaScript implicitly converts the number to a string. This is a simple and commonly used technique.

Using toString():

This is the simplest method and simply converts the number to its base-10 string representation.

 
let num = 12345.6789;
let str = num.toString(); // str will be "12345.6789"
 

Using Number.toFixed():

This method formats the number with a fixed number of decimal places

 
let num = 12345.6789;
let str = num.toFixed(2);
// str will be "12345.68" (rounded to 2 decimal places)
 

Using Number.toExponential():

This method formats the number in exponential notation with a specified number of digits after the decimal point.

 
let num = 12345.6789;
let str = num.toExponential(4);
// str will be "1.2346e+04" (4 digits after the decimal point)
 

Using Number.toPrecision():

This method formats the number with a fixed number of significant digits.

Using Intl.NumberFormat:

This object provides locale-aware formatting options, including currency, percentage, and unit formatting.

 
// toPrecision 
let num = 12345.6789;
let str = num.toPrecision(5);
// str will be "12346" (5 significant digits)
 
 
//NumberFormat
 
let num = 12345.6789;
let formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});
let str = formatter.format(num); // str will be "$12,345.68"