Handle trailing 0s Trigger changes to the input when it happens.
Jeremy D

Jeremy D commited on 2021-11-16 16:31:38
Showing 1 changed files, with 25 additions and 0 deletions.

... ...
@@ -73,6 +73,24 @@
73 73
 			options[option] = methodOrProps[option]
74 74
 		}
75 75
 
76
+		// Parse a float with 0s at the end.
77
+		// Reference: https://stackoverflow.com/questions/4868556/how-do-i-stop-parsefloat-from-stripping-zeroes-to-right-of-decimal
78
+		function customParseFloat(number)
79
+		{
80
+			if (isNaN(parseFloat(number)) !== false)
81
+				return number;
82
+
83
+			let toFixedLength = 0;
84
+			let str = String(number);
85
+
86
+			// You may add/remove seperator according to your needs
87
+			let arr = str.split(options.separator);
88
+			if (arr.length === 2) 
89
+				toFixedLength = arr[1].length;
90
+
91
+			return parseFloat(str).toFixed(toFixedLength);
92
+		}
93
+
76 94
 		function setNewValue(container, value)
77 95
 		{
78 96
 			if (options.onBeforeSetNewvalue !== undefined)
... ...
@@ -90,9 +108,16 @@
90 108
 				$(container).val(value);
91 109
 			else if (options.type === 'number')
92 110
 				$(container).val(parseInt(value));
111
+			// Handle floats/decmials with 0s at the end.
112
+			else if ((options.disallowTrailingZero === undefined || options.disallowTrailingZero === false) && value[value.length - 1] == 0)
113
+				$(container).val(customParseFloat(value));
93 114
 			else
94 115
 				$(container).val(parseFloat(value));
95 116
 
117
+			// By default, we should trigger a change to the container.
118
+			if (options.ignoreChangeTrigger === undefined || options.ignoreChangeTrigger === false)
119
+				$(container).trigger('change');
120
+
96 121
 			if (options.onAfterSetNewvalue !== undefined)
97 122
 				options.onAfterSetNewvalue(this, event, container, value);
98 123
 		}
99 124