Last active
August 29, 2015 14:07
-
-
Save cunneen/beec6fd204b7b89f4b75 to your computer and use it in GitHub Desktop.
DO NOT USE THIS, IT HAS A BUG. Keeping it for illustration purposes.
A little thing I knocked up to safely scale a javascript number using strings to avoid floating point issues.
The bug is where the multipleOfTenAsNumber has more digits than the original number. It doesn't work in that case. E.g. console.log(safeScale("109.87654",10000000000));…
This file contains 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
// if you try this in javascript: | |
// 10.2 * 100 | |
// you get this: | |
// 1019.9999999999999 | |
/** Safely scale a number. Just a hacky little demo. | |
* @param {string} numberAsString the number you want to scale e.g. 10.987654 | |
* @param {number} multipleOfTenAsNumber the number you want to scale by e.g. 1000 | |
* @returns {safeScale.result} the safely scaled number e.g. 10987.654 | |
*/ | |
function safeScale(numberAsString, multipleOfTenAsNumber) { | |
var numberParts, result, numZerosInMultipleOfTen; | |
numZerosInMultipleOfTen = Math.round(Math.log(multipleOfTenAsNumber) / Math.log(10)); // e.g. for multipleOfTenAsNumber=1000, will return 3 | |
numberParts = numberAsString.split("."); | |
result = Number(numberParts[0]) * multipleOfTenAsNumber ; // integer calculation | |
result += Number(numberParts[1].substr(0, numZerosInMultipleOfTen) ); // add the rest of the whole part | |
result += Number("0." + numberParts[1].substr(numZerosInMultipleOfTen)); // add the fractional part. | |
return result; | |
} | |
//console.log(safeScale("10.20",100)); | |
// 1020 | |
//console.log(safeScale("10987.654",1000)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment