Set decimal places in angular based on different currencies

Posted By : Anil Kumar | 26-Sep-2017

Problem Identification: Decimal places always needs to be fixed for user inputs and also for the result shown to the user. We set the decimal places for the input fields to restrict and notify a user for reliable input data. We also fix the decimal places for displaying the data that is understandable for user and other machines.

In java script it is easy to fix the decimal places but in angular it is difficult to do. It is more difficult when it is not common for all the input and output units.

We have different types of currencies like INR, USD, BTC, ETH e.t.c and diffrent quantity fields which also have their different scale set. 

Solution:  

(i) Get currency scale from java

 $scope.getCurrencyScale = function(marketId) {
    for (let i = 0; i < $scope.marketList.length; i++) {
        console.log("CHK first" + $scope.marketList.length);
        if ($scope.marketList[i].id == marketId) {
            $scope.scaleSet = $scope.marketList[i].limitCurrency.scale;
            $scope.scaleSetQuantity = $scope.marketList[i].nominalCurrency.scale;
            break;
        }
    }

};
 

by calling this function we will get the scale set for currency and scale set for quantity. This function will called for each input and output units where we want to fix the decimal places.

(ii) Function for geting the length of number after the decimal place

 function decimalPlaces(number) {
     if (number.toString() != number.toString().split('.')) {
         return number.toString().split('.')[1].length;
     }
     return 0;
 }
 

(iii) Now create a function for validating the decimal places for the currency field

 $scope.checkValue = function(val, val1) {
    if (val1 >= 0) {
        console.log(decimalPlaces(val1), val)
        if (decimalPlaces(val1) > val) {
            $scope.data.priceValue = true;

        } else {
            $scope.data.priceValue = false;

        }
    }
}
 

(iv) Function for validating the quantity input and output fields

 $scope.checkValueQuantity = function(val, val1) {
    if (val1 >= 0) {
        console.log(decimalPlaces(val1), val)
        if (decimalPlaces(val1) > val) {
            $scope.data.quantityValue = true;

        } else {
            $scope.data.quantityValue = false;
        }
    }
}
 

(v) Uses of these functions in view pages

 

only up to {{scaleSetQuantity}} decimal place allowed

only up to {{scaleSet}} decimal place allowed

About Author

Author Image
Anil Kumar

Anil is a Web Developer who specializes in creating dynamic and beautiful web projects and has good experience of working in distributed teams.

Request for Proposal

Name is required

Comment is required

Sending message..