JavaScript Program to Convert Float to String
Converting a float to a string in JavaScript becomes necessary when dealing with numerical values represented as strings. In this article, we will explore the process of converting floating-point numbers into strings in JavaScript.
Table of Content
- Method 1: Using String() Constructor
- Method 2: Using toString() Method
- Method 3: Using Template Literals
- Method 4: Using String Concatenation
- Method 5: Using String Interpolation
- Method 6: Using toLocaleString() Method
- Method 7: Using toFixed() Method
Method 1: Using String() Constructor
The String() constructor can be used to convert a float to a string:
Example: Here is the practical implementation of the above method.
const floatValue = 3.14159265;
const strValue = String(floatValue);
console.log(typeof strValue);
console.log(strValue);
Output
3.14159265
Method 2: Using toString() Method
You can use the toString() method for coverting float numerical values into a string:
Example: Here is the practical implementation of the above method.
const floatValue = 2.71828;
const strValue = floatValue.toString();
console.log(strValue);
Output
2.71828
Method 3: Using Template Literals
You can use template literals to convert a float to a string:
Example: Here is the practical implementation of the above method.
const floatValue = 42.123;
const strValue = `${floatValue}`;
console.log(strValue)
Output
42.123
Method 4: Using String Concatenation
You can use string concatenation to convert a float to a string:
Example: Here is the practical implementation of the above method.
const floatValue = 99.99;
const strValue = '' + floatValue;
console.log(strValue)
Output
99.99
Method 5: Using String Interpolation
You can use string interpolation (backticks) to convert a float to a string:
Example: Here is the practical implementation of the above method.
const floatValue = 0.1234;
const strValue = `Value: ${floatValue}`;
console.log(strValue)
Output
Value: 0.1234
Method 6: Using toLocaleString() Method
The toLocaleString() method can be used to format a float as a string with localization options:
Example: Here is the practical implementation of the above method.
const floatValue = 1000.25;
const strValue = floatValue.toLocaleString();
console.log(strValue)
Output
1,000.25
Method 7: Using toFixed() Method
The toFixed() method can be used to convert a float to a string, specifying the number of decimal places.
Example: Here is the practical implementation of the above method.
const floatValue = 5.6789;
const strValue = floatValue.toFixed(2);
console.log(strValue);
Output
5.68
Contact Us