Assign number input to number variable? [duplicate] - reactjs

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 11 months ago.
I'm fairly new to JavaScript and wanted to convert one of my calculation spreadsheets to something I can use on a web page. However, the calculation gives me an incorrect result.
Here's my JavaScript:
<script type="text/javascript" language="JavaScript">
function calc() {
var onerepmax = document.wodCalculate.oneRepMax.value;
var percent = document.wodCalculate.percentOfOneRepMax.value / 100;
var addkg = document.wodCalculate.plusKg.value;
var zwischenschritt = onerepmax * percent;
var gewicht = zwischenschritt + addkg;
document.getElementById("weight").innerHTML = gewicht;
};
</script>
and here's the HTML:
<form action="" id="wodCalculate" name="wodCalculate">
<table cellspacing="0" cellpadding="10" border="0">
<tr><td>1 Rep Max</td><td><input type=text name="oneRepMax" value=""> kg<br></td></tr>
<tr><td>% vom 1RM</td><td><input type=text name="percentOfOneRepMax" value=""> %<br></td></tr>
<tr><td>Plus x kg</td><td><input type=text name="plusKg" value=""> kg<br></td></tr>
<tr><td><input type="button" value="Calculate" onClick="calc()"></td></tr>
</table>
</form>
<div id="weight">Weight</div>
It works fine up to the point of multiplying the "onerepmax" with the "percent". However, once it gets to the point of adding the "addkg" to the result of the multiplication (i.e. giving me the "gewicht"), the result becomes incorrect.
For example, I want to get 10% of 100kg and add 10kg. Instead of 20kg, the calculation result is 1010.
Thanks for your help!

The value of an input is always a string, so + ends up being string concatenation ("10" + "10" is "1010", as opposed to 10 + 10 which is 20).
If you're using an input type="number" (the OP isn't, but others finding this answer may) and the browser supports them, you can use valueAsNumber instead:
var onerepmax = document.wodCalculate.oneRepMax.valueAsNumber;
If you're using type="text" or the browser doesn't support valueAsNumber:
You can convert user-input values using parseInt(value, 10) (the 10 = decimal, base 10) if they're meant to be whole numbers, e.g.:
var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);
That's just one option, though, you have several:
The unary + operator: value = +value will coerce the string to a number using the JavaScript engine's standard rules for that. The number can have a fractional portion (e.g., +"1.50" is 1.5). Any non-digits in the string (other than the e for scientific notation) make the result NaN. Also, +"" is 0, which may not be intuitive.
var onerepmax = +document.wodCalculate.oneRepMax.value;
The Number function: value = Number(value). Does the same thing as +.
var onerepmax = Number(document.wodCalculate.oneRepMax.value);
The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.
// (Same as the first one above)
var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);
The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.
var onerepmax = parseFloat(document.wodCalculate.oneRepMax.value);
So, pick your tool to suit your use case. :-)

The problem is that you're "adding" a string, not a number. The + operator in JavaScript has multiple semantics, and as soon as one operand is a string, it will do string concatenation.
To prevent that, convert the string to a number with the unary + operator.

Related

React input type="number" for floats

I want to have an input field of type="number". (So that on mobile phones the numeric keyboard will appear). The problem is, that all my values are in cents: 1EUR = 100 Cents and I want to display a comma as a decimal separator (German format), so onChange will multiply the value with 100, and when the value is rendered, it is devided by 100.
But when I type "5." after typing the next number the "." will get lost. The same happens with a ",".
I couldn't find any component already implemented that does this by using input type="number" instead of type="text".
So does anyone know such a library or a way to implement it, that does not include having two inputs, one for Cents and one for Euros?
I think the number input type can handle the German comma system. So there might not be a need to manually change a 2,5 input into a 2.5.
If you use this changeHandler on a number input
const changeHandler = e => {
const val = e.target.value
console.log(2 * val)
setNumber(val)
}
the val variable will be a usual float while you see a comma in the input.

Roman Number Calculator

I have to make an assignment wherein I have to implement the Roman Numerals along with the rules that are followed while doing calculations on them, contained in this link
http://www.periodni.com/roman_numerals_converter.html
I don't want the code, just help. I have gone with two approaches till now:
Using constants, I have declared the roman numerals as constants, and then after getting the input, I am left with the choice to decode the string input, which I later dropped.
Using hash. I have declared a hash with the numerals, then after getting the input, I am converting the string using to_sym method into there corresponding value. After this, I have taken an array containing the decimals of the roman numerals, and I intend to compare those with the input.
I am stuck at this part. I don't know how to compare here. Also, I don't want to sort the input array, because then calculations would go wrong.
Can anyone help me with how to proceed? Not the code, just steps.
This is what I have done so far:
class Conversion
hash ={ :I => 1, :V => 5, :X => 10, :L => 50, :C => 100, :D => 500, :M => 1000}
result = 0
value = []
hash_values = hash.values
puts "enter input string"
input = gets.chomp.upcase.split(//)
input.each do |i|
value <<  hash[i.to_sym]
end
for i in value do
if value[i] > value[i+1]
result = result + value[i]
else
result = result + (value[i+1] - value[i])
end
end
puts result
end
If u run the code, you'll see that while I try to compare in the last loop it is taking the index for calculations. Same happened when I tried doing the same using two hashes. I can't use any gem or external libraries cause that is the requirement.
The idea is to create a tree where every node have two childrens: the left one is what to substract and the right one is what to add.
Once you get a string, you find the most valued letter and make it the first node like this:
XLIX
L
/ \
X IX
Then you run this function recursively on the children nodes until the node is trivial (like XX or III).
The final step is to recursively calculate the result.

How to sum up two Scope values in AngularJS

var selPage2 = $scope.selPage + $scope.itemsPerPage;
$scope.selPageUp = selPage2;
for example if value of selPage is 50 and value of itemsPerPage is 10 and I want to display my value in HTML element like
{{selPageUp}}
Angular JS will make connection of this two strings and will display it like 5010, but I want to sum up two values to display number 60. How to do that? Example if I change operator from + to * it will multiply value and display 500 it will work on way I want. Help please?
If they are integers:
var selPage2 = parseInt($scope.selPage) + parseInt($scope.itemsPerPage);
Otherwise:
var selPage2 = parseFloat($scope.selPage) + parseFloat($scope.itemsPerPage);
The $scope.selpage and $scope.itemPerPage are probably of type String. if they would be Integers it would sum up fine. so first you have to convert this string to an Integer of Float with parseInt() or parseFloat(). 2 Strings do multiply because * is a Math function so it will automatically TRY to convert these strings in values.

How to substring of a string in matlab array

I have a matlab cell array of size 20x1 elements. And all the elements are string like 'a12345.567'.
I want to substitute part of the string (start to 9th index) of all the cells.
so that the element in matrix will be like 'a12345.3'.
How can I do that?
You can use cellfun:
M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these
MM = cellfun( #(x) [x(1:7),'3'], M, 'uni', 0 )
Resulting with
ans =
a12345.3
b12345.3
For a more advanced string replacement functionality in Matlab, you might want to explore strrep, and regexprep.
Another method that you can use is regexprep. Use regular expressions and find the positions of those numbers that appear after the . character, and replace them with whatever you wish. In this case:
M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these - Taken from Shai
MM = regexprep(M, '\d+$', '3');
MM =
'a12345.3'
'b12345.3'
Regular expressions is a framework that finds substrings within a larger string that match a particular pattern. In our case, \d is the regular expression for a single digit (0-9). The + character means that we want to find at least one or more digits chained together. Finally the $ character means that this pattern should appear at the end of the string. In other words, we want to find a pattern in each string such that there is a number that appears at the end of the string. regexprep will find these patterns if they exist, and replace them with whatever string you want. In this case, we chose 3 as per your example.

ExtJS: How to get decimal number value

I used decimalSeparator property of numberfield and set it to ',' (comma). Now I have problem reading value as number and doing math with it.
I first tried simple:
var v = form.getForm().getValues().myfield / 2
As soon s I type comma, v becomes NaN.
Then I tried:
var v = Ext.util.Format.number(form.getForm().getValues().myfield, "0.000,00") / 2
As soon a I type comma, v becomes 0.
I also tried combinations with /i in format string but id didn't help either.
What am I missing?
The problem is that getValues does not work as you expect. From the documentation of getValues (emphasis mine):
Note: The values are collected from all enabled HTML input elements within the form, not from the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the value can potentially be the emptyText of a field.
If you want to ensure that you have a decimal value, you will have to do something like the following:
var v_string = form.getForm().getValues().myfield; //get the string
v_string = v_string.replace(",", "."); //replace ',' with '.'
var v = (+v_string) / 2; //convert the value to a decimal and divide by 2
EDIT
You could also try using the getFieldValues (i.e. form.getForm().getFieldValues()) method instead of the getValues method. This should act as though you had called getValues on every form field.
This should work.
var value = parseFloat("5000,5".replace(",", "."));

Resources