Parsing integers in AngularJS - javascript

I am using AngularJS in one of our application.
In the code below, while loading the page the expression addition (number, valuetoadd) parses correctly and give output as 1+1=2 but while changing the input it doesn't parse correctly and it gives output as `1+2=12'.
Where do I need to change?
<div ng-controller='MathsController'>
<input type="range" min="0" max="100" step="1" value="1" ng-model='valuetoadd'/>
<p>Addition table of <b>{{valuetoadd}}</b></p>
<div ng-repeat='number in numbers'>
{{number}} + {{valuetoadd}} = {{ addition(number,valuetoadd) }}
</div>
</div>
<script type="text/javascript">
function MathsController($scope)
{
$scope.valuetoadd= 1;
$scope.numbers =[1,2,3,4,5,6,7,8,9,10];
$scope.addition = function(number,valuetoadd)
{
return number+valuetoadd;
}
}
</script>

May be number beging passed as a string.
Try:
$scope.addition = function(number, multiplier)
{
return + number + multiplier;
}
+ would convert the string into number.
EDIT:
Now, I see that multiplier is passed as string.
So IT has to be converted instead...
Sorry that I did not read the code carefully.
$scope.addition = function(number, multiplier)
{
return number + +multiplier;
}
Thank you #Artur for pointing this out.

Seems like the root of the problem lies here:
https://github.com/angular/angular.js/issues/1189
Also read this SO topic: Two-way binding with range and number input in AngularJS
As a workaround you can use the solutions proposed by thefrontender and tosh shimayama.
It's worth noticing, though, that it is the multiplier who requires parsing to integer, not the number. See my comment to your question.

Another quick fix is to multiply value by 1 before addition. This will force JavaScript to convert value from string to integer.
Example:
{{value*1 + 10}}

You need to coerce the variables into some sort of numeric type (values from HTML inputs are passed as string by default)
$scope.addition = function (number, multiplier) {
return number + parseInt(multiplier, 10);
}

Related

Im making calculator and when i add numbers 1+1 in my input i get answer 1. why

input value = "1+1" but when i console.log(salyga) i am getting answer "1" . Also if I only put + in input and I console log it I am getting answer NaN, I don't understand why math is not working.
Also if I change input type="number" I'm getting this error (The specified value "+" cannot be parsed, or is out of range.)
let salyga = document.querySelector(".container__langai--salyga");
const vienas = document.querySelector("#vienas");
const one = +vienas.value
vienas.addEventListener("click", number1);
function number1() {
salyga.value += one
}
const lygu = document.querySelector("#lygu");
const equal = lygu.value
lygu.addEventListener("click", opLygu);
const plius = document.querySelector("#plius");
const plus = plius.value
plius.addEventListener("click", opPlius);
function opLygu() {
console.log(parseFloat(salyga.value))
}
function opPlius() {
salyga.value += plus
}
<input value="" type="text" placeholder="0" class="container__langai--salyga"></input>
<button id="vienas" class="number" value="1">1</button>
<button id="lygu" value="=" class="operator">=</button>
<button id="plius" value="+" class="operator">+</button>
To solve that problem, here's information. Text that are get from tags are always String, it doesn't matter even if you set the input's type to number, so convert it to either int or float by using the parseInt() and the parseFloat() respectively. A sample down below is shown to demonstrate the correct usage.
alert(parseInt(document.getElementById("input_name").value));
alert(parseFloat(document.getElementById("input_name").value));
Extracted from w3Schools:
This function determines if the first character in the specified string is a number. If >it is, it parses the string until it reaches the end of the number, and returns the number > as a number, not as a string.
Note: Only the first number in the string is returned!
So when you pass 1+1 to the parseFloat, it will return only 1.
Your code document.querySelector("#vienas"); produces a collection of DOM elements, not a single element as you seem to be expecting. It does not matter if only 1 element is found, it still returns a collection (with 1 item in it).
To get the item directly, use getElementById():
const vienas = document.getElementById("vienas");

Retrieving number value from input instead of object

I am trying to write a small program to determine the common factors between two numbers. I am having a problem getting the numbers, though. Here is my HTML code:
<p>Please input two numbers to find the common factors between them.</p>
First number:<input type="number" id="firstNumber"></br>
Second number:<input type="number" id="secondNumber"></br>
<button onclick="commonFactors(document.getElementById('firstNumber'),
document.getElementById('secondNumber'))">Submit</button>
However, instead of getting the numbers back, the console returns the following:
"<input type='number' id='firstNumber'>" "<input type='number'
id='secondNumber'>"
With the quotes. Can you tell me what I'm doing wrong?
Not sure it matters, but here's the JS:
function commonFactors(num1, num2) {
console.log(num1, num2);
var counter=Math.min(num1, num2);
var factors=[];
var k=0;
for (i=1; i<counter; i++) {
if (num1%i==0) {
if (num2%i==0) {
factors[k]=i;
}
}
k+=1;
}
};
because document.getElementById('firstNumber') is refering to the input, use +document.getElementById('firstNumber').value notice the + because the values you get from an input are of type string so we use the + to transform them to a number
Note: you can use a function instead of the + it's called parseInt() for integers and parseFloat() for float numbers
the result is
<button onclick="commonFactors(parseInt(document.getElementById('firstNumber').value),
parseInt(document.getElementById('secondNumbe').value)">Submit</button>
You want to get the value of the input, not the input itself :
document.getElementById('firstNumber').value

TypeError: this.state.modifedGrowth.toFixed is not a function

I am working with react and I have input box having initial value but user can change that value. from backend I am value like 0.01999 so I use Math.round but that is allowing me to add decimal value and if I am using toFixed it gives me error
TypeError: this.state.modifedGrowth.toFixed is not a function can please anyone tell me how to do that?
here is my code
<input
type="text"
// value={Math.round(this.state.modifedGrowth * 100) / 100}
value={this.state.modifedGrowth.toFixed(2).toString()}
onChange={e => this.updateGrowthValue(e.target.value)}
onBlur={e => this.props.updateModifiedGrowth(e.target.value)}
/>
Thanks in advance
From the limited source there, it looks like this.state.modifedGrowth is a string. Strings don't have a .toFixed() method - if it's numerical data you're expecting convert it to a number first - Number(this.state.modifedGrowth)
I know this not the right solution but we can say it's fix I change it into string and manipulated that
componentDidMount() {
let modifedProgramGrowth = '';
if (this.props.modifedProgramGrowth .toString().includes('.')) {
let GrowthArr= this.props.modifedGrowth
.toString()
.split('.');
modifedProgramGrowth =
GrowthArr[0] + '.' + GrowthArr[1].substr(0, 2);
} else {
modifedGrowth = this.props.modifedGrowth ;
}
this.setState({ modifedProgramGrowth });
}

Converting string to int/float in jQuery

I am getting a value from a div :
<div id="test">100</div>
And what I want to do is to get the value with jQuery, raise with 50% and show the value.
$number= $('#test').text() //getting the value, without parseInt or parseFloat?
$newNumber = $number * 0,5 //show the result of this
I often end up with NaN, so I'd like to have a guidance on that. Thank you.
Suppose we have following markups:
<div id="test">100</div>
<div id="result"></div>
what you are looking for can be achieved as following (without using parseInt() or parseFloat() functions)
var number = $('#test').text();
var result = Number(number) + (number * 0.5);
$('#result').html(result);
You have error in your code, just fix it with:
$number * 0.5
Using dot, not comma.

JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}

Categories

Resources