JavaScript Program to Convert Float to String
Here are the various methods to convert float to string in JavaScript
1. Using String() Function
The String() function is one of the most commonly used and simplest ways to convert a float to a string. It works by converting the given value into its string representation.
let n = 123.45;
let s = String(n);
console.log(s);
Output
123.45
- String(num) converts the float num into a string.
- This method is simple and widely supported for basic type conversion.
2. Using .toString() Method
Every JavaScript object has the toString() method, which returns a string representing the object. The toString() method can be used on a float to convert it to a string.
let n = 123.45;
let s = n.toString();
console.log(s);
Output
123.45
- num.toString() converts the number num to its string representation.
- It is similar to using String(), but this is an instance method that works directly on the number object.
3. Using Number.toFixed() Method
If you need to control the number of decimal places in the string representation, you can use toFixed(). This method formats the float to a fixed number of decimals and returns it as a string.
let n = 123.456789;
let s = n.toFixed(2);
console.log(s);
Output
123.46
- num.toFixed(2) converts the float to a string with exactly two decimal places.
- toFixed() rounds the float to the specified number of decimals and returns the result as a string.
4. Using String() with Template Literals
Another simple method to convert a float to a string is by using template literals. Template literals automatically convert any expression inside ${} to a string.
let n = 123.45;
let s = `${n}`;
console.log(s);
Output
123.45
- ${num} inside backticks converts the float num into a string.
- This approach is concise and very useful when combining variables with strings.
5. Using concat() Method
The concat() method is typically used to combine two or more strings, but it can also be used to convert a float to a string by concatenating an empty string with the float.
let n = 123.45;
let s = ''.concat(n);
console.log(s);
- .concat(num) converts the float num into a string by concatenating it with an empty string.
- This approach works similarly to String() but is less commonly used for this purpose.
Conclusion
The most common and efficient method to convert a float to a string in JavaScript is using the String() function or .toString() method. These methods are simple, widely supported, and work for various data types, not just floats. If you need control over the number of decimal places, toFixed() is a useful option. Template literals and the concat() method can also used depending on the context, especially when combining strings and variables.