2016-05-31 49 views
0

我試圖做一個貨幣/數字輸入/輸出沒有舍入。AngularJS貨幣/數字輸出沒有舍入

我遇到的使用貨幣的問題是雙重的,(1)一旦輸入了第三個數字,它就舍入第二位小數,(2)它甚至允許輸入第三個數字。如果您注意到我的del()函數,它會刪除數字的結尾,但顯示可能是:$ 27.46。該字符串實際上可能是27.45606020,並且退格將刪除用戶甚至無法看到的數字。

目前我有一些hacky代碼甚至不會使用AngularJS的貨幣或數字,並使用過濾器來防止小數點後兩位數字,以及添加小數點時,我擁有它,所以它只能被添加一次。

{{checkTotal | dropDigits}

.filter('dropDigits', function() { 
    return function(floatNum) { 
     return String(floatNum) 
      .split('.') 
      .map(function (d, i) { return i ? d.substr(0, 2) : d; }) 
      .join('.'); 
    }; 
}) 

.controller('tipController', function($scope) { 

    // Numpad 
    $scope.checkTotal = '0.00'; 

    $scope.clicked = function (label) { 
    if($scope.checkTotal === '0.00') { 
     $scope.checkTotal = label; 
    } else { 
     $scope.checkTotal += label; 
    } 
    }; 

    // Prevent multiple decimals 
    $scope.clickedDot = function() { 
     if (($scope.checkTotal.indexOf('.') < 0) || ($scope.checkTotal === '0.00')) { 
     if (($scope.checkTotal === '0.00') || ($scope.checkTotal === '')) { 
      $scope.checkTotal = '0.'; 
     } else { 
      $scope.checkTotal += '.'; 
     } 
     } 
    }; 

    $scope.del = function() { 
     $scope.checkTotal = $scope.checkTotal.slice(0, -1); 
    }; 

}); 

回答

0

我能夠解決與另一個我的問題,如果發言

$scope.clicked = function(label) { 
    if ($scope.checkTotal === '0.00') { 
    $scope.checkTotal = label; 
    } else { 
    if (($scope.checkTotal.indexOf('.') != -1) && ($scope.checkTotal.substring($scope.checkTotal.indexOf('.')).length > 2)) { //if there is a decimal point, and there are more than two digits after the decimal point 
     label.preventDefault(); 
    } else { 
     $scope.checkTotal += label; 
    } 
    } 
}; 
1

您可以使用Math.floor來捨去小數位而不捨去舍入。將floor中的值乘以100,然後在內部做所需的數學運算,然後除以100得到正確的結果大小。

請看下面的演示或這個fiddle

angular.module('demoApp', []) 
 
\t .controller('mainController', MainController); 
 
    
 
function MainController($timeout) { 
 
\t var vm = this; 
 
    
 
    angular.extend(vm, { 
 
    \t input: 10.25, 
 
     total: 0, 
 
     calcTip: function() { 
 
     \t // 10% tip // 2 decimal places no rounding. 
 
      // floor calc. from this SO answer 
 
      // http://stackoverflow.com/questions/4187146/display-two-decimal-places-no-rounding 
 
      vm.total = Math.floor(vm.input * 1.1 * 100)/100; 
 
     } 
 
    }); 
 
    
 
    vm.calcTip(); // initial calc. 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="demoApp" ng-controller="mainController as mainCtrl"> 
 
    <input ng-model="mainCtrl.input" ng-change="mainCtrl.calcTip()"/> 
 
    <br/> 
 
    <strong>{{mainCtrl.total | currency}}</strong> 
 
</div>

+0

如果用戶只放入說「5」或$ .05,在你的榜樣它讀取出$ 0.50? – nightowl

+0

Nvm ..我編輯小提琴[這裏](https://jsfiddle.net/gk81xc50/)來解決它。我認爲這解決了我的問題,現在我唯一想弄清楚的是,如何將其轉換爲我的控制器?你有一個輸入ng-change,但我有按鈕,從$ scope.clicked添加他們的'標籤'

{{checkTotal}}
? – nightowl

+0

我已經更新了我的答案。這只是相對的計算。現在它是總價值(小費+輸入值)。 – AWolf