Skip to content

Instantly share code, notes, and snippets.

@bbars
Created September 25, 2020 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbars/7f9cf4718eef77fbdf9b800b40c2b7c0 to your computer and use it in GitHub Desktop.
Save bbars/7f9cf4718eef77fbdf9b800b40c2b7c0 to your computer and use it in GitHub Desktop.
Format repeating decimals as 1/3 -> "0.3(3)"
function formatRepeatingDecimal(num) {
num = num.toString();
var p = num.split('.');
if (p.length === 1) {
return p[0];
}
// match parts (prefix, repeating, suffix):
var m = /^(\d*?)(\d{1,})\2{2,}(\d*?)$/.exec(p[1]);
if (!m) {
return num;
}
// remove repeatings:
var m2;
while (m2 = /^(\d+)\1+$/.exec(m[2])) {
m[2] = m2[1];
}
// check if suffix is a natural (but broken) continuation of a repeating suffix:
if (m[3] !== '') {
// suffix is an eventually captured repeating part:
if (m[3] === m[2]) {
m[3] = '';
}
// suffix is a rounded repeating part:
m2 = +m[2];
var m3 = +m[3];
m3 *= Math.pow(10, m[2].length - 1);
if (Math.abs(m3 - m2) <= 1) {
m[3] = '';
}
}
// return original num if it isn't actually repeating in the math sense:
if (m[3]) {
return num;
}
// if prefix is empty, copy from the repeating part:
if (m[1] === '') {
m[1] = m[2];
}
return p[0] + '.' + m[1] + '(' + m[2] + ')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment