(val: string | number)
| 263 | * e.g. `getPrecisionSafe(100)` return `0`. |
| 264 | */ |
| 265 | export function getPrecision(val: string | number): number { |
| 266 | val = +val; |
| 267 | if (isNaN(val)) { |
| 268 | return 0; |
| 269 | } |
| 270 | |
| 271 | // It is much faster than methods converting number to string as follows |
| 272 | // let tmp = val.toString(); |
| 273 | // return tmp.length - 1 - tmp.indexOf('.'); |
| 274 | // especially when precision is low |
| 275 | // Notice: |
| 276 | // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`. |
| 277 | // (see https://jsbench.me/2vkpcekkvw/1) |
| 278 | // (2) If the val is less than for example 1e-15, the result may be incorrect. |
| 279 | // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`) |
| 280 | if (val > 1e-14) { |
| 281 | let e = 1; |
| 282 | for (let i = 0; i < 15; i++, e *= 10) { |
| 283 | if (mathRound(val * e) / e === val) { |
| 284 | return i; |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | return getPrecisionSafe(val); |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * Get precision with slow but safe method |
no test coverage detected
searching dependent graphs…