Converting string to floating number Javascript - javascript

I have a issue using variable in if condition. I have three variable where one is a string type and two more in Json. Here settings.DecimalDigits value is 2 or anything more than 2.
var controlValue = integer + '.' + mantissa;
controlValue = parseFloat(controlValue).toFixed(settings.DecimalDigits);
integer & mantissa will have a certain value which is stored in controlValue as string. controlValue is then compared with other two variables (settings.MaxValue & settings.MinValue) in IF condition but its not going through condition as it type is string type
if (controlValue > settings.MaxValue)
controlValue = settings.MaxValue;
if (controlValue < settings.MinValue)
controlValue = settings.MinValue;
In my parsing all three variables will have three values in floating type
controlValue = 123.23 or 123.00
settings.MaxValue = 99.99
settings.MinValue = -99.99
Please help so that the parsing goes through the IF Condition

.toFixed() turns your number back into a string. If you want it back to a number again, then you need to use parseFloat on it. There are probably better ways to do this, but building on your existing code, you would make controlValue a number that would work in your if statement by calling parseFloat() again like this:
var controlValue = integer + '.' + mantissa;
controlValue = parseFloat(parseFloat(controlValue).toFixed(settings.DecimalDigits));
FYI, it might make more sense to just handle the number entirely as a number rather than go back and forth to strings several times:
var controlValue = parseFloat(integer + '.' + mantissa);
var filter = Math.pow(10, settings.DecimalDigits);
controlValue = Math.round(controlValue * filter) / filter;
or perhaps even just this:
var controlValue = parseFloat(integer + '.' + mantissa.toString().substr(0, settings.DecimalDigits));

jfriend00's answer helped me solve my problem. Solution below:
var controlValue = e.target.value; //get value from input
controlValue = Number(controlValue); //Converting the string to number
// Number format parses through if condition
if (controlValue > settings.MaxValue)
controlValue = Number(settings.MaxValue);
if (controlValue < settings.MinValue)
controlValue = Number(settings.MinValue);
// if the value is having a mantissa 00. It will be rejected by Number() function. So next line its converted again to string format using .toFixed() function.
var controlValue = controlValue.toFixed(settings.DecimalDigits);
// Splitting the value into two parts integer and mantissa
integer = controlValue.split('.')[0];
if (typeof integer == 'undefined' || integer == null || integer == "" || isNaN(integer))
integer = 0;
// settings.DecimalDigits is the variable to set any default number of mantissa required to appear.
mantissa = controlValue.split('.')[1];
if (typeof mantissa == 'undefined') {
mantissa = "";
for (i = 0; i < settings.DecimalDigits; i++)
mantissa += '0';
}
// Finally you have the result
controlValue = integer + '.' + mantissa;

Related

How to convert a long string (more than 16 digits) into numbers

this is a function just increment one number into array
but the problem i interface when i put alot of numbers into array (more than 16 digits)
when i use parseInt() just returned 16 correct numbers and more than that be zero
6145390195186705000
and expected
6145390195186705543
the function
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = parseInt(numbersInString);
var theNumbersPlusOne = theNumbers + 1;
var result = String(theNumbersPlusOne).split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
Just expanding on my above comment with another solution...
You've exceeded the maximum safe integer value. (Number.MAX_SAFE_INTEGER, which equals 9007199254740991). Numbers larger than this are not supported with standard integer types in javascript, or rather there's not enough precision to represent them. Anything larger than this is represented in scientific notation and the extra digits are truncated and represented only as zeroes.
With that said, you don't even need to convert the array to a string to an integer just to increment it. You can just increment the individual digits in the array, starting at the end and working your way forwards to "carry the 1" so to speak.
var plusOne = function(digits) {
for(let i = digits.length - 1; i > -1; i--)
{
if(digits[i] == 9)
{
digits[i] = 0;
if(i == 0)
digits = [1].concat(digits);
}
else
{
digits[i]++;
break;
}
}
return digits;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
You can use BigInt to handle this problem.
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = BigInt(numbersInString);
var theNumbersPlusOne = theNumbers + BigInt(1);
var result = theNumbersPlusOne.toString().split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

JS - summing elements of arrays

I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...
The values of these arrays come from fields (html)
No idea how to deal with that ;D
Thanks for your help
If you wanna look at my code, here's what it looks like :
var polynome = [];
for (var i=0; i<=degree; ++i) {
polynome[i] = document.getElementById(i).value;
}
var a = document.getElementById("a").value;
var tempArray = [];
var quotient = [];
quotient[degree+1] = 0;
for (var i=degree; i>=0; --i) {
tempArray[i] = a * quotient[i+1];
quotient[i] = polynome[i] + tempArray[i];
}
document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;
array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them
you need to cast both elements in arrays to integer
try this
parseInt( array1[i] ) + parseInt( array2[i] )
The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:
var a = '2';
var b = '3';
the unary + operator will convert integers and floats, but it's a bit obscure:
+a + +b
parseInt will convert to integers:
parseInt(a, 10) + parseInt(b, 10);
parseFloat will convert integers and floats:
parseFloat(a) + parseFloat(b);
The Number constructor called as a function will convert integers and floats and is semantic:
Number(a) + Number(b);
Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:
a - -b

Javascript add count to a number with comma

So I have this
var str=document.getElementById('elem').innerHTML;
str=parseInt(str)+1;
<span id="elem">1,500</span>
and I can't get it to take the entire number and add one (+1) to the number without taking comma off. Can you suggest something?
Remove the commas by replacing them with an empty string, then you can parse the string.
Remember the second parameter in the parseInt method that specifies the base, so that it doesn't use base 8 for zero padded values.
var num = parseInt(str.replace(/,/g, ''), 10) + 1;
If you want to put the changed number back formatted with commas, you can use:
var s = num.toString();
for (var i = s.length - 3; i > 0; i -= 3) {
s = s.substr(0, i) + ',' + s.substr(i);
}
document.getElementById('elem').innerHTML = s;

Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)

I'm converting a CSV file to a local 2D array. I wanted to know if there is a better way to convert strings to floats/int rather then using regex followed by a parseFloat() / parseInt.
Ideas / Suggestions?
// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
number = {};
number.valid = false;
number.value = str;
// if we see a number then convert it to a floating point or integer
if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {
number.valid = true;
number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
if(number.value.search(/[\.]/) >= 0) {
number.value = parseFloat(number.value); // replace floating point
} else {
number.value = parseInt(number.value); // replace integers
}
}
return number; // number.valid = true or false;
}
var num = numex("1.101");
alert(num.value);
I don't think you need to use regexp at all. Try this:
var num = {};
num.value = new Number(str);
num.valid = !isNaN(num.value);
Number constructor is more strict than parseInt and parseFloat in that it does not accept strings like 10aaa or 1.2bbb so there is no need to perform a regexp check.
I simplified the code greatly and used something similar to what LeZuse did.
isNaN(value) || value == ""
https://github.com/designpro/jCSV

Categories

Resources