The Wayback Machine - https://web.archive.org/web/20241005040730/https://www.geeksforgeeks.org/how-to-convert-string-into-float-in-javascript/
Open In App

How to convert string into float in JavaScript?

Last Updated : 21 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will convert a string into a float in Javascript. We can convert a string into a float in JavaScript by using some methods which are described below:

Methods to Concert String into Float:


Method 1: By using Type Conversion of JavaScript

In this method, we will use the Type Conversion feature of JavaScript which will convert the string value into float.

Example: Below program demonstrates the above approach 

javascript
// Javascript script
// to convert string
// to float value

// Function to convert
// string to float value
function convert_to_float(a) {

    // Type conversion
    // of string to float
    let floatValue = +a;

    // Return float value
    return floatValue;
}

//Driver code
let n = "55.225";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
    " Type of " + n + " = " + typeof n);

n = "-33.565";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

Output
Converted value = 55.225 Type of 55.225 = number
Converted value = -33.565 Type of -33.565 = number

Method 2: By using parseFloat() Method

In this method, we will use the parseFloat() method which is an inbuilt function in JavaScript that is used to accept the string and convert it into a floating point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. 

Example: Below program demonstrates the above approach 

javascript
// Javascript script
// to convert string
// to float value

// Function to convert
// string to float value
function convert_to_float(a) {

    // Using parseFloat() method
    let floatValue = parseFloat(a);

    // Return float value
    return floatValue;
}

//Driver code
let n = "245.165";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);
n = "-915.55";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

Output
Converted value = 245.165 Type of 245.165 = number
Converted value = -915.55 Type of -915.55 = number


Special Case: In French, float numbers are written by the use of a comma (, ) as a separator instead of a dot(.) as a separator.

Example:

The value 245.67 in French is written as 245, 67

To convert a French string into a float in JavaScript we will first use replace() method to replace every (, ) with (.) then follow any of the above-described methods. 

Example: Below program demonstrates the above approach 

javascript
// Javascript script
// to convert string
// to float value

// Function to convert
// string to float value
function convert_to_float(a) {
    // Using parseFloat() method
    // and using replace() method
    // to replace ', ' with '.'
    let floatValue = parseFloat(a.replace(/, /, "."));

    // Return float value
    return floatValue;
}

//Driver code
let n = "245, 165";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

n = "-915, 55";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

Output
Converted value = 245.165 Type of 245.165 = number
Converted value = -915.55 Type of -915.55 = number

Method 3: By using the eval() function

In this method, we will use the eval() method which is an inbuilt function in JavaScript that is used to evaluate the string return result. If the string contains a number then it converts it from string to number and then returns it and if contains other than the number it returns NaN i.e, not a number. Example: Below program demonstrates the above approach 

JavaScript
// Javascript script
// to convert string
// to float value

// Function to convert
// string to float value
function convert_to_float(a) {
    // Type conversion
    // of string to float
    let floatValue = eval(a);

    // Return float value
    return floatValue;
}

//Driver code
let n = "55.225";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

n = "-33.565";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

Output
Converted value = 55.225 Type of 55.225 = number
Converted value = -33.565 Type of -33.565 = number

Method 4: By using Number() constructor

In this method, we can use the Number() constructor which is a built-in function in JavaScript to convert a string into a number, including floats. It parses the argument as a float (or integer) and returns the result.

Example:

JavaScript
// Using Number() constructor to convert a string into a float
let stringNumber = "3.14";
let floatNumber = Number(stringNumber);
console.log(floatNumber); // Output: 3.14

Output
3.14

Method 5: By using Unary Plus Operator

The unary plus (+) operator can be used to convert a string to a number, including floats. It is a simple and concise way to perform this conversion.

Example: Below program demonstrates the above approach

JavaScript
// Javascript script
// to convert string
// to float value

// Function to convert
// string to float value
function convert_to_float(a) {
    // Using unary plus operator
    let floatValue = +a;

    // Return float value
    return floatValue;
}

//Driver code
let n = "123.456";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

n = "-789.012";

// Call function
n = convert_to_float(n);

// Print result
console.log("Converted value = " + n +
        " Type of " + n + " = " + typeof n);

Output
Converted value = 123.456 Type of 123.456 = number
Converted value = -789.012 Type of -789.012 = number




Previous Article
Next Article

Similar Reads

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() ConstructorMethod 2: Using toString() MethodMethod 3: Using Template Literal
2 min read
How to convert String to Float in PHP ?
Converting a string to a float in PHP is a common requirement when handling numeric data stored in string format. This conversion allows the numeric string to be used in calculations or comparisons, ensuring accurate manipulation of data within the program. There are many methods to convert a string into a number in PHP, some of them are discussed
3 min read
How to Convert a Float Number to the Whole Number in JavaScript?
Given a float number and the task is to convert a float number to a whole number using JavaScript. Below are various methods to convert float numbers to whole numbers in JavaScript: Table of Content Math.floor (floating argument)Math.ceil (floating argument) Math.round (floating argument)Math.trunc (floating argument)parseInt (floating argument)dou
4 min read
How to convert rgb() color string into an object in JavaScript ?
Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values. Example:Input: rgb(242, 52, 110) Output: { red: 242, green: 52, blue: 110 } Input: rgba(255, 99, 71, 0.5) Output: { red: 255, green: 99, blue: 71, alpha: 0.5 } Approach: To achieve this we us
2 min read
Convert user input string into regular expression using JavaScript
In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object Regular expressions (RegExp) are patterns used to
2 min read
Convert string into date using JavaScript
In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date. A string can be converted into a date in JavaScript through the following ways: Table of Content Using JavaScript Date() constructorUsing JavaScript toDateString() methodUsing Date.parse() methodUsing Int
3 min read
How to convert a string into kebab case using JavaScript ?
Given a string with space-separated or camel case or snake case letters, the task is to find the kebab case of the following string. Examples: Input: Geeks For GeeksOutput: geeks-for-geeksInput: GeeksForGeeksOutput: geeks-for-geeksInput: Geeks_for_geeksOutput: geeks-for-geeksBelow are the approaches used to convert a string into a kebab case using
3 min read
JavaScript Program to Convert an Array into a String
We have been given an array as an input that consists of various elements and our task is to convert this array of elements into a string by using JavaScript. Below we have added the examples for better understanding: Example: Input: arr= [1,2,3,4,5,6]Output: 1,2,3,4,5,6Table of Content Using arr.join() MethodUsing arr.toString() MethodUsing JSON.s
4 min read
How to convert long number into abbreviated string in JavaScript ?
We are given a long number and the task is to convert it to the abbreviated string(eg.. 1234 to 1.2k). Here 2 approaches are discussed with the help of JavaScript. Approaches to Convert Long Number to Abbreviated String:Table of Content Using JavaScript methodsUsing Custom functionUsing logarithmsUsing Intl.NumberFormatUsing RecursionUsing External
6 min read
How to convert image into base64 string using JavaScript ?
In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript. ApproachHere we will create a gfg.js file which will include JavaScript code and one gfg.html file.Now we will put onchange on the input type and this will execute a functi
2 min read
How to convert a string into a integer without using parseInt() function in JavaScript ?
In JavaScript, there is a simple function parseInt() to convert a string to an integer. In order to know more about the function, you can refer to this. In this article, we will learn how to convert the string to an integer without using the parseInt() function. Advantage of parseInt() over this method. The parseInt() function converts the number w
3 min read
How to format a float in JavaScript ?
Format a float number means to round off a number up to the given decimal place, ceiling, flooring, etc. There are many operations used to format the float number which are given below: Math.ceil() Method float.toFixed() Method Math.round() Method Math.floor() Method float.toExponential() Method number.toPrecision() Method Math.ceil(), float.toFixe
4 min read
JavaScript Program to Check if a Number is Float or Integer
In this article, we will see how to check whether a number is a float or an integer in JavaScript. A float is a number with a decimal point, while an integer is a whole number or a natural number without having a decimal point. Table of ContentUsing the Number.isInteger() MethodUsing the Modulus Operator (%)Using Regular ExpressionsWe will explore
2 min read
How to add float numbers using JavaScript ?
Given two or more numbers the task is to get the float addition in the desired format with the help of JavaScript. There are two methods to solve this problem which are discussed below: Table of Content Using parseFloat() and toFixed() method Using parseFloat() and Math.round() method Using Number() and Intl.NumberFormat method Using parseFloat() a
2 min read
How to Parse Float with Two Decimal Places in JavaScript?
JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number. Below are the approaches to parse float to two decimal places in JavaScript: Table of Content Using parseFloat() MethodUsing Custom parseFloat Method Approach 1: Using parseFloat() MethodThe parseFloat() method converts a string to a floating-p
2 min read
How to convert string into a number using AngularJS ?
In this article, we will see how to convert a string into a number in AngularJS, along with understanding its implementation through the illustrations. Approach: The parseInt() method is used for converting the string to an integer. We will check whether the string is an integer or not by the isNumber() method.Example 1: In the first example, the s
2 min read
How to Convert a JSON String into an SQL Query?
JSON to SQL conversion is complicated because both have different structure. but this the help of the article you can easily convert JSON into SQL. We will use JavaScript language for conversion. Approach: Using JavaScript Validate JSON Format.Parse the JSON String into a JSON ObjectExtract Values from the JSON Object.Concat extract values and deve
2 min read
How to convert a String into Number in PHP ?
Strings in PHP can be converted to numbers (float/ int/ double) very easily. In most use cases, it won't be required since PHP does implicit type conversion. This article covers all the different approaches for converting a string into a number in PHP, along with their basic illustrations. There are many techniques to convert strings into numbers i
4 min read
How to convert an Integer Into a String in PHP ?
The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. In this article, we will learn many methods. Table of Content Using strval() function.Using Inline variable parsing.Using Explicit Casting.Using sprintf() FunctionUsing concatenation with an Empty StringUsi
3 min read
Convert boolean result into number/integer in JavaScript
A JavaScript boolean represents one of two values: true or false. However, if one wants to convert a variable that stores boolean value, into integer "0" or "1", they can do so using multiple approaches. We will look into some of them in this article. The most popular methods are: Using ternary or conditional operator Using unary + operator. Using
3 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code <h1 st
2 min read
How to convert arguments object into an array in JavaScript ?
The arguments object is an array-like object that represents the arguments passed in when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. This object can be converted into a proper array using two approaches: Method 1: Using the Array.from() method: The Array.from()
5 min read
How to convert UTC date time into local date time using JavaScript ?
Given an UTC date and the task is to convert UTC date time into local date-time using JavaScript toLocaleString() function. Syntax: var theDate = new Date(Date.parse('DATE_IN_UTC')) theDate.toLocaleString() Example 1: This example converts UTC date time into local date time using JavaScript. C/C++ Code <body> <h1 style="color:green;
1 min read
How to convert speech into text using JavaScript ?
In this article, we will learn to convert speech into text using HTML and JavaScript. Approach: We added a content editable "div" by which we make any HTML element editable. C/C++ Code <div class="words" contenteditable>     <p id="p"></p> </div> We use the SpeechRecognition object to convert the speech i
2 min read
How to convert a plain object into ES6 Map using JavaScript ?
The task is to convert a JavaScript Object into a plain ES6 Map using JavaScript. we're going to discuss a few techniques. To understand the difference between a map and an object please go through the Map vs Object in JavaScript article. Below are the following approaches to converting a plain object into ES6 Map using JavaScript: Using map() Cons
2 min read
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, there you can use the below methods for the conversio
4 min read
JavaScript Program to Convert Minutes into Hours
Minutes and hours are units of time. These units are essential for managing schedules, planning activities, and organizing daily routines. These units are essential for managing schedules, planning activities, and organizing daily routines. Formula Used: Formula to convert minutes into hours : 1 minute = 1/60 hourBelow are the approaches for conver
2 min read
JavaScript Program to Convert Hours into Minutes
Hours and Minutes are units of time. These units are essential for managing schedules, planning activities, and organizing daily routines. We are going to explore how we can convert hours into minutes using JavaScript. Example: // Formula to convert hours into minutes: 1 hour = 1*60 minutesBelow are the approaches for converting hours into minutes
2 min read
JavaScript Program to Convert Minutes into Seconds
Minutes and seconds are important for planning schedules and managing daily activities. Understanding this conversion helps in better time management. These units are essential for managing schedules, planning activities, and organizing daily routines. Example: // Formula to convert minutes into seconds:1 minute = 1 * 60 secondsBelow are the approa
2 min read
JavaScript Program to Convert Hours into Seconds
Hours and Seconds are units of time. These units are essential for managing schedules, planning activities, and organizing daily routines. Here we will convert hours into seconds using JavaScript. Example:// Formula to convert hours into seconds1 hour = 1*60 * 60 secondsBelow are the approaches for converting hours into seconds in JavaScript: Table
2 min read