T Evon
T Evon

Reputation: 43

how to have one decimal point for numbers using angularJS

i've seen a few things for regExp but for some reason i'm thinking this should be more simple. Maybe not. Maybe regExp fits this perfectly and i don't understand the concept. Which, i do not. I don't understand regExp and thats why i haven't used it.

but what i am trying to do is build a basic calculator using AngularJS. My calculator has an ng-disable feature for my equals sign. So its not allowed to be pressed and won't work until a leftOperand, operator, and rightOperand are clicked. Now i don't want to disable the decimal when its clicked, because i might need it for my rightOperand.

But in essence i want my code to reflect "if there is an operator, then the rightOperand is rightOperand + any other Operand entered. Otherwise, the leftOperand is going to equal the leftOperand + any other Operand Entered. (which this is currently working ex. 333 + 45948594 works. The decimal works too. But! it can allow 333.464.6454 and i don't want that).

Trying to implement: Also/And/Or/If a decimal is put into the leftOperand, then no other decimals are allowed for the leftOperand. If the rightOperand has a decimal, then no other decimals are allowed for the rightOperand.

what is the simplest way to go about this?

https://codepen.io/tevon/pen/Moewba

this is my setDecimal method, but its allowing more than 1 decimal for both the right and left operands

$scope.setDecimal = function (decimalEntered) {
        if ($scope.operator){
            $scope.rightOperand += decimalEntered;
        };
        else {$scope.leftOperand += decimalEntered;
        };

i was givin something like this: if string.indexOf('.') > -1 // then do something but honestly, i'm not sure how to about the 'do something' part works, nor the -1 portion

not using Jquery.

Upvotes: 0

Views: 61

Answers (2)

Michał Sałaciński
Michał Sałaciński

Reputation: 2266

You were right when you thought about indexOf - you just need to stop execution of this method if there's already dot there - and easiest way is return

if ($scope.rightOperand.indexOf('.')>-1) return;

LINK

Upvotes: 0

jsdevel
jsdevel

Reputation: 1619

So you're building your operand as a string. That means you can test the operand you currently have on your scope to see if it has a point using .indexOf.

if (myVariable.indexOf('.') === -1) myVariable += '.';

Upvotes: 1

Related Questions