Angular.js square root for this calculator - angularjs

I have searched far and wide looking for a simplified square root short code version and found plenty of versions in JavaScript, Java, jQuery ... but nothing in Angular.js.
Below is my code:
<body align"center"><form><h1 align="center">Quick 2 number Angular.js Calculator </h1></center>
<center><h6>- Teaching aide only -</h6></center>
<div ng-app="">
<input type="number" ng-model="numb1" placeholder="number1" size="5px"><br />
<input type="number" ng-model="numb2" placeholder="number2" size="5px"><br />
<b style="color:#0000FF"><button disabled>+</button>
<button disabled>-</button>
<button disabled>X</button>
<button disabled>/</button></b>
<button style="background-color:lime;color:green" disabled>ENT</button>
<button style="background-color:orange;color:red">CLR</button>
<center><h2>Answers Below</h2></center>
<p>My first expression: {{ numb1 }} ; {{ numb2 }}</p>
<p>Addition: {{ numb1 + numb2 }}</p>
<p>Subtraction: {{ numb1 - numb2 }}</p>
<p>Multiplication: {{ numb1 * numb2 }}</p>
<p>Division: {{ numb1 / numb2 }}</p>
<p>Square of {{ numb1 }}<small><sup>2</sup></small> is {{ numb1 * numb1 }}<br>Square of {{ numb2 }}<small><sup>2</sup></small> is {{ numb2 * numb2 }}</p>
<p>Cube of {{ numb1 }}<small><sup>3</sup></small> is {{ numb1 * numb1 * numb1 }}<br>Cube of {{ numb2 }}<small>
<sup>3</sup></small> is {{ numb2 * numb2 * numb2 }}</p>
</form>

The best way is to use filter for this:
angular.module('app', []).filter('sqrt', function() {
return function(number) {
return Math.sqrt(number);
};
});
<div ng-app="app">
<input type="number" ng-model="numb1" placeholder="number1" size="5px"><br />
<div>{{ numb1 | sqrt }}</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>

In this case, javascript has what you want. You need to pass an argument to the Math.sqrt function for this. Here is an example from MDN. You could create a service or a directive to wrap around this function, but angularjs itself doesn't have this function.
function calcHypotenuse(a, b) {
return(Math.sqrt((a * a) + (b * b)));
}
console.log(calcHypotenuse(3, 4));
// expected output: 5
console.log(calcHypotenuse(5, 12));
// expected output: 13
console.log(calcHypotenuse(0, 0));
// expected output: 0
If you have to create a custom solution, I would recommend looking at the javascript code for the function itself to see how it's implemented. You can go to Firefox for example, to download their implementation.
I was able to find the algorithm, but not the code there after I downloaded it.
Square Root
A simple iterative algorithm is used to compute the greatest integer
less than or equal to the square root. Essentially, this is Newton's
linear approximation, computed by finding successive values of the
equation:
x[k]^2 - V x[k+1] = x[k] - ------------
2 x[k]
...where V is the value for which the square root is being sought. In
essence, what is happening here is that we guess a value for the
square root, then figure out how far off we were by squaring our guess
and subtracting the target. Using this value, we compute a linear
approximation for the error, and adjust the "guess". We keep doing
this until the precision gets low enough that the above equation
yields a quotient of zero. At this point, our last guess is one
greater than the square root we're seeking.
The initial guess is computed by dividing V by 4, which is a heuristic
I have found to be fairly good on average. This also has the
advantage of being very easy to compute efficiently, even for large
values.
So, the resulting algorithm works as follows:
x = V / 4 /* compute initial guess */
loop t = (x * x) - V /* Compute absolute error */ u = 2 * x /* Adjust by tangent slope */ t = t / u
/* Loop is done if error is zero */ if(t == 0)
break
/* Adjust guess by error term */ x = x - t
end
x = x - 1
The result of the computation is the value of x.

In Html :
call the cube and square function defined in angular controller
<input type="number" ng-model="numb1" placeholder="number1" ng-change="cube(numb1)" size="5px"><br />
<p>Square of {{ numb1 }}<small><sup>2</sup></small> is {{ cubeResult }}</p>
In Controller(*.js) :
define a function that returns square and cube of particular value
$scope.cubeResult =0;
$scope.square= function(value){
$scope.cubeResult = value * value;
};
$scope.cube = function(value){
$scope.cubeResult = value * value * value;
};

Related

ng-pattern for only number with no decimal

Need ng-pattern for restricting entry of decimal in input type number.I have used
ng-pattern="/^[0-9]$/"
to get the result but its not showing error on 1.0,2.0,3.0 etc.
Example:
2.0 = fail
2 = pass
3.0=fail
3=pass
<div class="col-md-5 col-md-offset-7">
<input type="number" min="0" class="form-control" id="equalizingFactor"
name="equalizingFactor" ng-model="flatVariable.equalizingFactor"
itle="Equalizing Factor" ng-maxlength="3" ng-pattern="/^[0-9]$/"
message="The field should contain only numbers with no decimal places"
ng-readonly="flatVariable.pgmInd30"/>
</div>
Should only have numbers no decimals included.
These should work fine:
ng-pattern="/^[0-9]*$/" // 0 or more numbers
ng-pattern="/^[0-9]+$/" // 1 or more numbers
ng-pattern="/^\d*$/" // 0 or more numbers
ng-pattern="/^\d+$/" // 1 or more numbers

How do I restrict angular-xeditable to only positive numbers?

I have the following code. Is there an attribute to restrict to just positive numbers?
<td><span e-step="0.001" editable-number="myNumber" onaftersave="updateValue()">{{ myNumber }} </span></td>
Try e-min="0" to set the minimum value
and e-max="100" to set a maximum.

AngularJS repeat list with 2 index in a row [(1,2), (3,4), (5,6), etc]

Here is my sample List ,
$scope.list_element = [1,2,3,4,5,6,7,8,9,10];
I want to Iterate this List into Multiple Rows, each Row should contain 2 elements from the List.
required output,
1 , 2
3 , 4
5 , 6
7 , 8
9 , 10
i am getting like this,
1
2
3
4
5
6
7
8
9
10
I tried this using ng-repeat i.e: ng-repeat="val in list_element"
<div ng-repeat="val in list_element">
<p>{{val}}</p>
</div>
i know this is wrong.. it will give one by one... but i want to iterate 2 values in a row instead one...
The problem is the <p> tag will create a new line by default each time you execute it. And if you replaced it with anything else such as or just text inside a div
<div ng-repeat="val in list_element">
{{ val }}
</div>
this will output 12345678910
In order to solve it, you can use the special $odd or $even like this
<div ng-repeat="val in list_element tracked by $index">
<br ng-if="$odd"/>{{ val }}
</div>
notice that the <br/> will only add a new line to output when it's odd. Adjust it to get the result you are seeking.

Display number always with 2 decimal places in <input>

I have a float value for the ng-model that I would like to always display with 2 decimal places in the <input>:
<input ng-model="myNumb" step ="0.01" type="number">
This works for most case when "myNumb" has decimal. But it will not force display of the 2 decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer(30)
How can I force a display of 2 decimal place in the <input> field
AngularJS - Input number with 2 decimal places it could help...
Filtering:
Set the regular expression to validate the input using ng-pattern. Here I want to accept only numbers with a maximum of 2 decimal places and with a dot separator.
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal | number : 2" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
Reading forward this was pointed on the next answer ng-model="myDecimal | number : 2".
If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}, as in:
<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>
BREAKDOWN
'1.2-2' means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}:
A minimum of 1 digit will be shown before decimal point
It will show at least 2 digits after decimal point
But not more than 2 digits
Credit due here and here
{{value | number : fractionSize}}
like {{12.52311 | number : 2}}
so this will print 12.52
Simply use the number pipe like so :
{{ numberValue | number : '.2-2'}}
The pipe above works as follows :
Show at-least 1 integer digit before decimal point, set by default
Show not less 2 integer digits after the decimal point
Show not more than 2 integer digits after the decimal point
Did you try using the filter
<input ng-model='val | number: 2'>
https://docs.angularjs.org/api/ng/filter/number
Another shorthand to (#maudulus's answer) to remove {maxFractionDigits} since it's optional.
You can use {{numberExample | number : '1.2'}}
best way to Round off number to decimal places is that
a=parseFloat(Math.round(numbertobeRound*10^decimalplaces)/10^decimalplaces);
for Example ;
numbertobeRound=58.8965896589;
if you want 58.90
decimalplaces is 2
a=parseFloat(Math.round(58.8965896589*10^2)/10^2);
(Math.round(2.782061* 100 )/100).toFixed(2);
This will convert that into Two decimal places:
For Ex: 2.782061 ---> 2.78 two decimal Places
Use currency filter with empty symbol ($)
{{val | currency:''}}

Angular filter maximum decimals

I want to create a new filter such that i get an input, and i give the amount of maximum decimals to show and return a string that is formatted according to locale.
Input(number) Output for 1 decimal Output for 2 decimals
1.01 1 1.01 / 1,01
1.001 1 1
1.1 1.1 / 1,1 1.1 / 1,1
1 1 1
1000 1 000 / 1.000 / 1,000 1 000 / 1.000 / 1,000
I want to use angular's built in number filter for locale purposes, but i can't come up with how to remove decimals since if i do it after number filter, then i have a locale specific string, and i cant do it before, since i don't know how to round before i have used number:x
Any hints or ideas?
Added my own filter, implemented as such:
app.filter('numberNoDecimalsIfZeroFilter', function($filter) {
return function(value, fractionSize) {
//If has no decimals, then don't show
if(value%1 === 0){
fractionSize = 0;
}
return $filter('number')(value,fractionSize);
}
});
Used as such:
<div class="form-group">
<label class="control-label">Amount: </label>
{{::value.amount | numberNoDecimalsIfZeroFilter}}
</div>
You can't, see filter's implementation:
// format fraction part.
while (fraction.length < fractionSize) {
fraction += '0';
}
The filter always adds zeros. If you want to achieve what you want, you have to write your own filter.

Resources