AngularJS中如何校验小数点后第4位数字是否为非0值
AngularJS 实现数值小数点后第4位非0校验方案
1. 核心校验逻辑
和框架无关的通用判断逻辑,避开浮点数精度问题:
function checkFourthDecimalNonZero(num) { // 非法数值处理,可根据业务调整返回值 if (isNaN(parseFloat(num)) || !isFinite(num)) { return false; } // 转成保留4位小数的字符串,避免精度计算误差 const numStr = Number(num).toFixed(4); // 取小数点后第4位(下标从0开始,第4位对应索引3) const fourthDigit = numStr.split('.')[1]?.[3] ?? '0'; return fourthDigit !== '0'; }
测试用例效果:
checkFourthDecimalNonZero(23.8981)返回truecheckFourthDecimalNonZero(23.8980)返回falsecheckFourthDecimalNonZero(23)返回false
2. 控制器中直接使用
把方法挂载到$scope即可在逻辑、模板中调用:
angular.module('yourApp', []) .controller('yourController', ['$scope', function($scope) { $scope.targetNumber = 23.8981; $scope.checkFourthDecimal = function(num) { if (isNaN(parseFloat(num)) || !isFinite(num)) { return false; } const numStr = Number(num).toFixed(4); const fourthDigit = numStr.split('.')[1]?.[3] ?? '0'; return fourthDigit !== '0'; }; // 业务侧调用示例 $scope.validateResult = $scope.checkFourthDecimal($scope.targetNumber); }]);
模板中直接调用判断:
<div ng-app="yourApp" ng-controller="yourController"> <input type="number" ng-model="targetNumber" placeholder="输入数值"> <p ng-if="checkFourthDecimal(targetNumber)">小数点后第4位为非0值</p> <p ng-if="!checkFourthDecimal(targetNumber)">小数点后第4位为0或无第四位小数</p> </div>
3. 封装为表单校验指令(推荐复用场景)
如果需要在多处表单中使用该校验,封装为自定义指令更易用:
angular.module('yourApp', []) .directive('fourthDecimalNonZero', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$validators.fourthDecimalNonZero = function(modelValue, viewValue) { const value = modelValue || viewValue; // 空值默认放行,需要必填可配合原生required指令使用 if (!value) return true; if (isNaN(parseFloat(value)) || !isFinite(value)) return false; const numStr = Number(value).toFixed(4); const fourthDigit = numStr.split('.')[1]?.[3] ?? '0'; return fourthDigit !== '0'; }; } }; });
表单中使用方式:
<form name="numberForm"> <input type="number" name="numInput" ng-model="targetNumber" fourth-decimal-non-zero required > <span ng-if="numberForm.numInput.$error.fourthDecimalNonZero"> 提示:小数点后第4位不能为0 </span> </form>
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

