How to use replace and parseFloat methods In Javascript
In this method, we will use replace()method of JavaScript to replace every character other than numbers and decimal (.) with blank (“”). After then we can use parseFloat() method to make the string float or double. This method is more efficient than method 1.
The string.replace() is an inbuilt function in JavaScript which is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.
Syntax:
str.replace(A, B)
The parseFloat() is an inbuilt function in JavaScript which 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. It actually returns a floating point number parsed up to that point where it encounters a character that is not a Number.
Syntax:
parseFloat(value)
Example: This example shows the above-explained approach.
// JavaScript script to convert
// string currency to double
// Function to convert
function convert(currency) {
// Using replace() method
// to make currency string suitable
// for parseFloat() to convert
let temp = currency.replace(/[^0-9.-]+/g, "");
// Converting string to float
// or double and return
return parseFloat(temp);
}
// Driver code
// Currency in string
let string_currency = "$6542.45";
console.log("Currency value: " + string_currency);
// Converting currency
let doubleValue = convert(string_currency);
// Display currency
console.log("Converted to double: " + doubleValue);
// Currency in string
string_currency = "$357,545.45";
console.log("Currency value: " + string_currency);
// Converting currency
doubleValue = convert(string_currency);
// Display currency
console.log("Converted to double: " + doubleValue);
Output
Currency value: $6542.45 Converted to double: 6542.45 Currency value: $357,545.45 Converted to double: 357545.45
How to convert a currency string to a double value with jQuery or Javascript?
In this article, we will convert a currency string to a double value with jQuery or Javascript. There are two popular ways to convert currency string into float string using different JavaScript inbuilt libraries.
Contact Us