I have a set of form fields that have values like $1.00, $1654.31 and i would like to convert them to a numerical string only so i can calculate the values.
Im looping over each one, but keep getting NaN when i log to the console.
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val() ) );
});
each time it returns NaN, im wondering whether there is an easy way to make a dollar value string convert to a numerical value only for calculating ?
thanks in advance
Try
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace('$','') ) );
});
var numberWithoutDollar = numberWithDollar.replace(/^\$/, '');
You have to remove everything but numbers, .
, -
and +
.
$("input.costs").each(function( index) {
console.log( $(this).val() + parseFloat( $(this).val().replace(/[^\d\.\+-]/g, "") ) );
});
Examples:
parseFloat("-1.00".replace(/[^\d\.\+-]/g, ""))
// -1
parseFloat("+1654.31 ".replace(/[^\d\.\+-]/g, ""))
// 1654.31
刚刚跳过美元符号。
parseFloat($(this).val().substr(1))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.