After working with Float32Array values in AngularJS, I have noticed some unexpected behavior.
During my testing, I encountered the following scenarios:
angular.module("myApp", []).controller("myCtrl", function($scope) {
$scope.n = 0.2; // Displays as 0.2
$scope.arr1 = new Float32Array(1);
$scope.arr1[0] = 0.2; // 0,20000000298023224
$scope.arr2 = new Float64Array(1);
$scope.arr2[0] = 0.2; // Displays as 0.2
});
I am aware that the issue stems from 0.2 being a repeating binary fraction.
Do you have any suggestions on how to adjust the toString method (or another function) to handle lower precision and round decimals when necessary?
To address this problem, I created a directive that slightly improves the situation:
.directive("numberfloat", function(){
return {
scope: {n: "=model"},
template: '<input type="number" ng-model="m" ng-model-options="{getterSetter: true}"/>',
link: function($scope){
$scope.m = function(newVal){
if(newVal){
$scope.n = newVal;
}
return parseFloat($scope.n.toFixed(4));
}
}
}
})