Last active
December 21, 2015 00:39
-
-
Save Protonk/6222459 to your computer and use it in GitHub Desktop.
find significant digits. Useful for approximate equality tests where you care about orders of magnitude
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * sigDigitFind | |
| * | |
| * Determine position of most significant digit | |
| * | |
| * Returns a positive number for significant digits left of the radix | |
| * and a negative number for right of the radix. | |
| * | |
| * @param {String} inputFloat A String (optionally a Number) representing a | |
| * floating point number. | |
| * | |
| */ | |
| function sigdigitFind(inputFloat) { | |
| // .search() is 0 indexed, of course. We want 1 indexed pos | |
| // of most significant digit | |
| // Drop negative sign and coerce to string | |
| inputFloat = (Math.abs(parseFloat(inputFloat, 10))).toString(); | |
| // If significant digit is before the decimal point | |
| // return a positive number | |
| if (parseInt(inputFloat, 10) !== 0) { | |
| return +(inputFloat.search(/[1-9]/) + 1); | |
| } | |
| // We're searching a string, so we want to chop off the decimal point | |
| inputFloat = inputFloat.substring(inputFloat.indexOf('.') + 1); | |
| // Return a negative number otherwise | |
| return -(inputFloat.search(/[1-9]/) + 1); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment