MCPcopy
hub / github.com/frappe/erpnext / _round

Function _round

banking/src/lib/numbers.ts:167–221  ·  view source on GitHub ↗
(num: number, precision: number, rounding_method?: string)

Source from the content-addressed store, hash-verified

165}
166
167const _round = (num: number, precision: number, rounding_method?: string) => {
168
169 rounding_method = rounding_method || getSystemDefault('rounding_method') || "Banker's Rounding (legacy)";
170
171 const is_negative = num < 0 ? true : false;
172
173 if (rounding_method == "Banker's Rounding (legacy)") {
174 const d = cint(precision);
175 const m = Math.pow(10, d);
176 const n = +(d ? Math.abs(num) * m : Math.abs(num)).toFixed(8); // Avoid rounding errors
177 const i = Math.floor(n),
178 f = n - i;
179 let r = !precision && f == 0.5 ? (i % 2 == 0 ? i : i + 1) : Math.round(n);
180 r = d ? r / m : r;
181 return is_negative ? -r : r;
182 } else if (rounding_method == "Banker's Rounding") {
183 if (num == 0) return 0.0;
184 precision = cint(precision);
185
186 const multiplier = Math.pow(10, precision);
187 num = Math.abs(num) * multiplier;
188
189 const floor_num = Math.floor(num);
190 const decimal_part = num - floor_num;
191
192 // For explanation of this method read python flt implementation notes.
193 const epsilon = 2.0 ** (Math.log2(Math.abs(num)) - 52.0);
194
195 if (Math.abs(decimal_part - 0.5) < epsilon) {
196 num = floor_num % 2 == 0 ? floor_num : floor_num + 1;
197 } else {
198 num = Math.round(num);
199 }
200 num = num / multiplier;
201 return is_negative ? -num : num;
202 } else if (rounding_method == "Commercial Rounding") {
203 if (num == 0) return 0.0;
204
205 const digits = cint(precision);
206 const multiplier = Math.pow(10, digits);
207
208 num = num * multiplier;
209
210 // For explanation of this method read python flt implementation notes.
211 let epsilon = 2.0 ** (Math.log2(Math.abs(num)) - 52.0);
212 if (is_negative) {
213 epsilon = -1 * epsilon;
214 }
215
216 num = Math.round(num + epsilon);
217 return num / multiplier;
218 } else {
219 throw new Error(`Unknown rounding method ${rounding_method}`);
220 }
221}
222
223
224export const cint = (v: boolean | string | number, def?: boolean | string | number) => {

Callers 1

fltFunction · 0.85

Calls 2

getSystemDefaultFunction · 0.90
cintFunction · 0.85

Tested by

no test coverage detected