JavaScript input value issue [duplicate] - javascript

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 8 years ago.
The following doesn't work as expected:
function sum(x,y){
return x + y;
}
document.getElementById('submit').onclick = function(e)
{
//do someting
e.stopPropagation();
var value1 = document.getElementById('v1').value,
value2 = document.getElementById('v2').value;
var newSum = sum(value1, value2);
console.log(newSum);
}
There is something wrong with the values being picked up. It should return the sum and not "1+2=12"

Change
return x + y;
to
return parseInt(x) + parseInt(y);
You have to convert the values to numbers first, before adding them. If the numbers are floats, you can use parseFloat instead of parseInt.
Edit As suggested by RGraham in the comments, its always better to pass the radix (check parseInt's doc) explicitly. So, the code becomes
return parseInt(x, 10) + parseInt(y, 10);

For more accuracy:
function sum(x,y){
return parseFloat(x) + parseFloat(y);
}

You need to parse your value to an int as all values are passed as string in javascript.
value1 = parseInt(document.getElementById('v1').value, 10);
value2 = parseInt(document.getElementById('v2').value, 10);

use
parseInt
Syntax
var num = parseInt(string, radix);
Parameters
string
The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.
radix
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
function sum(x,y){
return parseInt(x,10) + parseInt(y,10);
}

Related

How to make 1 + 1 = 2 instead of 1 + 1 = 11 [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 7 years ago.
I am trying to add the number mathematically, but it keeps adding the number after it.
It takes the id number (begen), then it gets the number inside another div (kacbegen).
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (kacbegen + 1);
alert(toplam);
However, when doing the math (toplam), it alerts all the numbers.How to add the number mathematically ?
Convert it to number via adding a +:
var toplam = (+kacbegen + 1);
Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.
It looks like you're working with Strings (and thus a + b is the concatenation operator) when you want to be working with Number (so x + y would be addition)
Perform your favorite way to cast String to Number, e.g. a unary +x
var kacbegen = +$("#math" + begen).text();
You need to use parseInt to convert kacbegen, which is a String instance, to a Number:
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (parseInt(kacbegen) + 1);
alert(toplam);
The + operator, when used with a String on either side, will serve as a concatenation, calling Number.prototype.toString on 1.
You need to cast the contents to a number:
var contents = $("#math" + begen).text();
var kacbegen = parseFloat(contents);
You use kacbegen as a string. Please use as a integer use parseInt(kacbegen) + 1

Having trouble understanding function involving number addition

function NumberAddition(str) {
var nstr = str.match(/[0-9]+/g);
var total = 0;
if (nstr !== null)
for (var i = 0; i < nstr.length; i++) {
total += nstr[i]*1;
}
// code goes here
return total;
}
I was looking at answers in coderbyte.com and this was one of them. My question is about the total += nstr[i]*1 section. if I remove the *1 the answer is concatenated to "2344". However the answer should be 23+4+4=31. why is this?
The *1 forces the string in nstr[i] to be converted to a number. Another way to do that would be
total += +nstr[i];
The * (multiplication) operator is only meaningful for numbers, and the language definition stipulates that when its arguments are not numbers, they should be converted. Of course, if nstr[i] isn't really a number (unlikely in your case, if not impossible) then the result would be a NaN value. Similarly, the unary + operator also forces its operand to be converted to a number.
Multiplying a value by 1 is a way to ensure that it gets converted to a number if it isn't. When you add two things in JavaScript, if either is a string then the operation gets evaluated as string concatenation, not addition. Since the values in nstr were the result of a regular expression match, they are string values, not number values.
You can multiply a value by 1 to make sure that it is treated as a number. The canonical JavaScript way to do this is to use the unary + operator (total += +(nstr[i]);).
> "1"+1
"11"
> 1+"1"
"11"
> 1+1
2
> ("1"*1)+1
2
> (+"1")+1
2

Value keeps adding as string in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Addition turns into concatenation
Here's what I have...
var srate = Math.round(princ * intr * term * 100) / 100; //works fine
var dasvalue = princ + srate; //doesn't work
document.calc.pay.value = dasvalue;
The "var dasvalue = princ + srate;" adds the two sums up as strings.
100 + 1.4 = 1001.4
What am I doing wrong?
You can use the unary plus operator to cast to type Number, ensuring addition rather than concatenation:
var dasvalue = +princ + +srate;
princ is a string too. You can convert it to a Number with the unary + operator.
If your value in princ comes from an input you need to convert it into a number first.
var dasvalue = Number(princ) + srate;

How to parse float with two decimal places in javascript?

I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.
price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
and use:
var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143
or simply:
(22/7).round(3); // 3.143
To return a number, add another layer of parentheses. Keeps it clean.
var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:
function parseFloat2Decimals(value) {
return parseFloat(parseFloat(value).toFixed(2));
}
function parseFloat2Decimals(value,decimalPlaces) {
return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
ceil from lodash is probably the best
_.ceil("315.9250488",2)
_.ceil(315.9250488,2)
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)
will work also with a number and it's safe
You can use .toFixed() to for float value 2 digits
Exampale
let newValue = parseFloat(9.990000).toFixed(2)
//output
9.99
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
parseFloat(parseFloat(amount).toFixed(2))
You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.
To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.
#sd
Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.
Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options
Either use data as a string or
Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5.
You can store your price as a string
You can use
Number(string)
for your calculations.
example
Number("34.50") == 34.5
also
Number("35.65") == 35.65
If you're comfortable with the Number function , you can go with it.
Try this (see comments in code):
function fixInteger(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseInt(value);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseInt(value);
}
// apply new value to element
$(el).val(newValue);
}
function fixPrice(el) {
// this is element's value selector, you should use your own
value = $(el).val();
if (value == '') {
value = 0;
}
newValue = parseFloat(value.replace(',', '.')).toFixed(2);
// if new value is Nan (when input is a string with no integers in it)
if (isNaN(newValue)) {
value = 0;
newValue = parseFloat(value).toFixed(2);
}
// apply new value to element
$(el).val(newValue);
}
Solution for FormArray controllers
Initialize FormArray form Builder
formInitilize() {
this.Form = this._formBuilder.group({
formArray: this._formBuilder.array([this.createForm()])
});
}
Create Form
createForm() {
return (this.Form = this._formBuilder.group({
convertodecimal: ['']
}));
}
Set Form Values into Form Controller
setFormvalues() {
this.Form.setControl('formArray', this._formBuilder.array([]));
const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
this.ListArrayValues.forEach((x) => {
control.push(this.buildForm(x));
});
}
private buildForm(x): FormGroup {
const bindvalues= this._formBuilder.group({
convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2) --- option for two decimal value
});
return bindvalues;
}
I've got other solution.
You can use round() to do that instead toFixed()
var twoPlacedFloat = parseFloat(yourString).round(2)
The solution that work for me is the following
parseFloat(value)

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories