hussain
hussain

Reputation: 7083

How can i set just integer from string value?

I have angular options where i am displaying file Size but i am using variable value to calculate some bytes where i need just integer like if user select "1MB" i want to assign to variable maxMb 1. is it possible with javascript ?

ctrl.js

 var maxMb;
 $scope.FileSizeOptions = ["1MB","2MB","3MB","4MB","5MB"];
    $scope.$watch('selectedFileSize',function (Val) {
        maxMb = Val;
        console.log('File Size', maxMb);
    })

var maxBytes = 1000 * 1000 * maxMb;

Upvotes: 0

Views: 170

Answers (3)

Mike Cluck
Mike Cluck

Reputation: 32511

You can (ab)use parseInt and the fact that it will convert the string into an integer and will stop the conversion once it hits a non-numeric character.

console.log(parseInt('1MB', 10));  // 1
console.log(parseInt('2MB', 10));  // 2
console.log(parseInt('5MB', 10));  // 5
console.log(parseInt('10MB', 10)); // 10

Upvotes: 3

LethargicGeek
LethargicGeek

Reputation: 79

If you have control over the data set, I'd recommend setting fileSizeOption to be an array of objects that has both a display value and a size value. That way there's no hackity parsing of objects. See code snippet and codePen

http://codepen.io/Lethargicgeek/pen/BzEjPX

angular.module("myApp", []);

angular.module("myApp").controller("myCtrl", ctrlFn);

function ctrlFn() {
  var $ctrl = this;
  $ctrl.fileSizeOptions = [{
    size: 1,
    value: "1MB"
  }, {
    size: 2,
    value: "2MB"
  }, {
    size: 3,
    value: "3MB"
  }, {
    size: 4,
    value: "4MB"
  }, {
    size: 5,
    value:"5MB"
  }];
  $ctrl.onChange = onChange;

  function onChange() {
    $ctrl.maxMb = $ctrl.selectedFileSize.size;
    $ctrl.maxBytes = 1000 * 1000 * $ctrl.maxMb;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div ng-app="myApp">
  <div ng-controller="myCtrl as $ctrl">
    <select ng-model="$ctrl.selectedFileSize"
            ng-options="opt as opt.value for opt in $ctrl.fileSizeOptions"
            ng-change="$ctrl.onChange()">
    </select>
    
    <dl>
      <dt>$ctrl.selectedFileSize</dt>
      <dd>{{$ctrl.selectedFileSize}}</dd>
      
      <dt>$ctrl.maxMb</dt>
      <dd>{{$ctrl.maxMb}}</dd>
      
      <dt>$ctrl.maxBytes</dt>
      <dd>{{$ctrl.maxBytes}}</dd>      
    </dl>
  </div>
</div>

Upvotes: 1

castletheperson
castletheperson

Reputation: 33466

You could slice off the last two characters, and then use the unary + to coerce to an int, or replace all non-numeric characters and then coerce the value.

console.log(+'1MB'.slice(0, -2));
console.log(+'1MB'.replace(/\D/g, ''));

Upvotes: 0

Related Questions