scribbledecobble
scribbledecobble.blogspot.com
Pages
Home
Contents
A
…
K
There and back again
README
See also
Code
Number.prototype.decToBase = function(base) { const EPSILON = 1e-7, MAXD = 50; const digits = ["0","1","2","3","4","5","6","7","8","9", "a","b","c","d","e","f","g","h","i","j","k","l","m", "n","o","p","q","r","s","t","u","v","w","x","y","z"]; function posIntTo(i, base) { let num = ""; while (i > 0) { num = digits[i % base] + num; i = Math.floor(i/base); } return num; } function posFrcTo(f, base) { let num = ""; for (let d = 0; f > EPSILON && d < MAXD; d++) { let p = f * base; num += digits[Math.floor(p)]; f = p % 1; } return num; } const decNum = this, posN = Math.abs(decNum), posI = Math.floor(posN), posF = posN - posI, newI = posI > 0 ? posIntTo(posI, base) : "0", newF = posF > 0 ? posFrcTo(posF, base) : "0", newN = newF !== "0" ? newI + "." + newF : newI, num = decNum < 0 ? "-" + newN : newN; return num; } String.prototype.decFromBase = function(base) { const digits = {0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9, a:10,b:11,c:12,d:13,e:14,f:15,g:16,h:17,i:18,j:19,k:20, l:21,m:22,n:23,o:24,p:25,q:26,r:27,s:28,t:29,u:30,v:31, w:32,x:33,y:34,z:35}; function validate(str, b) { if (b < 2 || b > 36) { throw Error(b + " is an invalid base."); } str = str.toLowerCase(); for (let i = str.length - 1; i >= 0; i--) { let decVal = digits[str[i]]; if (!(decVal < b)) { throw Error("Invalid base " + b + " number."); } } return str; } function digitsToDec(strI, strF, b) { const strN = validate(strI + strF, b); let p = 1 / Math.pow(b, strF.length), numD = 0; for (let i = strN.length - 1; i >= 0; i--) { numD += digits[strN[i]] * p; p *= b; } return numD; } const num = this, isNeg = num[0] === "-", posN = isNeg ? num.slice(1) : num, parts = num.split("."), posI = parts[0], posF = parts.length === 2 ? parts[1] : "", decN = digitsToDec(posI, posF, base), decNum = num < 0 ? "-" + decN : decN; return decNum; } function decToBase(decNum, base) { return parseFloat(decNum).decToBase(base); } String.prototype.decToBase = function(base) { return decToBase(this, base); } function decFromBase(num, base) { return num.toString().decFromBase(base); } Number.prototype.decFromBase = function(base) { return decFromBase(this, base); }
Newer Post
Older Post
Home