Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.
Related
This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 3 years ago.
I want to take a number input (id="number") and save it as "x". Then make another variable, "y", that is 5% of "x". And then I want to add them together and save the result in a variable called "result".
Let's say that x = 100. Then y = 5. If I would just alert "y" it would alert the number 5 which is correct but the problem is that when I try to alert "result" (x+y) it alerts 1005 (it doesn't add the numbers just write them next to each other).
let x = document.getElementById("number");
let y = x*0.05;
var result = x+y;
alert(result);
Fist get value and so convert it to number:
Change :
var x = document.getElementById("number")
to :
var x = parseInt( document.getElementById("number").value )
Note : You must convert the input to a number even if type property be equal with number.
function fun() {
var x = document.getElementById('number').value;
console.log( typeof x)
var y = parseInt(document.getElementById('number').value);
console.log( typeof y)
}
<input type="number" id="number">
<button onclick="fun()">Go..</button>
you need a value for doing some calculation. so,
var x = document.getElementById("number").value;
"+" operator will concatenate if string value exist. var x is string value but automatic type casting will occur when var y=x*0.05. so you must cleary declaire "x is number" via parseInt().
var x = parseInt(document.getElementById("number").value);
Now "+" operator will work as you expected.
What's going on is x+y is performing string concatenation, not integer addition--which is what you want.
// String concatenation
console.log("100" + "5"); // outputs "1005"
// Integer Addition
console.log(100 + 5); // outputs "105"
That's the problem, but what's the solution?
The solution is to force integer addition with something like parseInt() (as Ehsan mentioned)
var x = parseInt( document.getElementById("number").value );
Worth noting is the fact that Ehsan uses document.getElementById("number").value, instead of document.getElementById("number")
This forces x to be an int, which will allow x+y to perform integer addition.
P.S. I should also note part of the reason for your problem is related to the fact that document.getElementById("number").value is a string, forcing a type conversion to take place
Addition ‘+’ concatenates strings
Almost all mathematical operations convert values to numbers. A notable exception is addition +. If one of the added values is a string, the other one is also converted to a string.
Then, it concatenates (joins) them:
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
Meaning that one of the operands (again, document.getElementById("number").value is a string) in an addition operation being a string forces both to become strings and get concatenated.
When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...
What I'm trying to do is to make a progress bar for donation. My html structure is:
<div class="hgoal" style="text-align: center;">My goal is to raise $<span id="mygoal">9,999.00</span></div>
<div class="donation-total">Total Donation<span id="total-donation">1,000.00</span></div>
my javascript so far is to get the innerHTML value of mygoal and total-donation.
var mygoal = document.getElementById("mygoal").innerHTML;
var totalgoal = document.getElementById("total-donation").innerHTML;
and I'm getting this as a result:
mygoal = "9,999.00";
total-donation = "1,000.00";
I believe this is a string and not an integer, and using parseInt() only give me the first digit number.
Can anyone give me an idea how can I make this into an integer that can use for computation? example:
mygoal + total-donation = 10,999.00
And also, any idea how can i get the percentage of this two varible?
Use .replace(/,/g,'') to replace commas, then you get the magic of type coercion to convert your string to a number during calculation...
var mygoal = document.getElementById("mygoal").innerHTML.replace(/,/g,'');
var totalgoal = document.getElementById("total-donation").innerHTML.replace(/,/g,'');
If you use + on strings, they will be appended to each other, but other mathematical operators (*/- etc...) will first coerce the strings into numbers. To force coercion, you can multiply by 1, or perhaps use Number("123123.123")...
Number(mygoal) + Number(totalgoal); // using addition, so coerce strings to numbers
(mygoal / total_donation) * 100; // does not need coercion
Your main issue is, that your numbers include colons. The parseFloat() call will work, once you replace these colons. You may use the following code to do so:
// define regexp to replace colons
var replaceColons = new RegExp(',', 'g');
// apply regex
num = num.replace(replaceColons, '');
mygoal=parseInt(mygoal.replace(/,/gi,"")) will give you mygoal=9999.
You should use parseFloat(), not parseInt() ...
More, you have to remove the commas from the string, since parseFloat() does not undertsand number formatting characters (like comma). So, for example:
mygoal = mygoal.replace(/,/g, '');
total_donation = total_donation.replace(/,/g, '');
To get the percentage of two numbers, use:
(mygoal / total_donation) * 100;
Note that in JavaScript you can't use 'minus' char (-) in variables names.
You could use for example 'underscore' char (_), or CamelCase, wich is the recommended style for variables in JavaScript.
You need to convert those Indian (maybe) numbers to valid Javascript numbers for the sum, then convert the output back to the initial format using Number.toLocaleString.
var mygoal = "9,999.00";
var total_donation = "1,000.00";
var total = Number((Number(mygoal.replace(/,/g, '')) + Number(total_donation.replace(/,/g, ''))).toFixed(2));
var finalResult = total.toLocaleString('en-IN',{minimumFractionDigits: 2 });
alert(finalResult);
I was trying with following script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#item1_number_1').keyup(function() {
var valone = $('#item1_number_1').val();
var valtwo = 5;
var total = ((valone) + (valtwo));
$('#item2_number_1').val(total.toFixed(2));
});
});
</script>
I do not get any result in the field. But when I assign multiple (*) instead of plus (+), I am getting result.
I cannot understand what the error is in "var total = ((valone) + (valtwo));"
You can only call toFixed on Numbers.
String * String will convert the strings to Numbers and multiply them giving you a Number.
String + String will concatenate the two Strings together giving you a String.
You need to convert the strings to Numbers manually before you try to add them together.
var total = (+valone) + (+valtwo);
Then Number + Number will add the two Numbers together giving you a Number.
The value of an input is always a string. "Adding" a string concatenates, giving another string. Strings do not have a toFixed method.
* however is unambiguously "multiply", giving a number and therefore a result.
var valone = parseFloat(document.getElementById('item1_number_1').value);
Use parseInt() to convert fetched value(valone ) to number, and calculate, something like this, please use this only when your number is not float(56.66),
var valone = parseInt($('#item1_number_1').val(), 10);
var valtwo = 5;
var total = ((valone) + (valtwo));
The fetched vaue is treated like string until you convert it into number.
UPDATE
After Archer pointed out, I came to know you are using toFixed() method, which supposed to expect float numbers. So in this case you should use parseFloat() as given below.
var valone = parseFloat($('#item1_number_1').val());
I think one of them is a string. Try parseInt(valone) to make it an int first.
The issue is the + operator can also be used to concat strings together. The * operator is ONLY for multiplication and therefore it implicitly converts your values to numbers.
So you either need to use parseInt, parseFloat, or Number to explicitly convert to a numeric type before using the + operator.
I have a variable that holds a number
var simpleNumber = 012345678;
I want to .split() this number and create an array that would be of each 3 numbers
the array should look like this
[012, 345, 678]
var splitedArray = simpleNumber.toString().split(/*how do i split this?*/);
it is part of a getRGB("ffffff") function, so i cant know what will be passed in.
Thanks
You can try:
var splittedArray = "012345678".match(/.../g);
function tridigit(n) {
return n.toString().match(/.{1,3}/g);
}
Note that if you prefix a number with a zero, it will be interpreted in octal. Octal literals are officially deprecated, but are supported for the time being. In any case, numbers don't have leading zeros, so it won't appear when you convert the number to a string.
Testing on Safari and FF, numbers with a leading 0 and an 8 or 9 are interpreted in base 10, so octal conversion probably wouldn't be a problem with your specific example, but it would be a problem in the general case.
Try this
var num = 123456789+"";// converting the number into string
var x1=num[0]+num[1]+num[2];//storing the individual values
var y1=new Array(x1);// creating a first group out of the first 3 numbers
var x2=num[3]+num[4]+num[5];
var y2=new Array(x2);// creating a second group out of the next 3 numbers
var x3=num[6]+num[7]+num[8];
var y3=new Array(x3);// creating a third group out of the next 3 numbers
var result=y1.concat(y2,y3);// concat all the 3 array
document.write(result);you get the output in the form of array
document.write("<br/>");
document.write(result[0]);
document.write("<br/>");
document.write(result[1]);
document.write("<br/>");
document.write(result[2]);
check the below link for the working example http://jsfiddle.net/informativejavascript/c6gGF/4/