John1984 John1984 - 7 months ago 17
Javascript Question

Convert a decimalized number into a fraction of eighths

Fairly sure this is a simple problem, but I'm having issues wrapping my head around it. Suppose I have a decimalized number:

1.25
1.5
2.75
2.45


How do I convert the decimal part to be shown as a fraction of eighths? e.g.

1 2/8
1 4/8
2 6/8
2 3/8 // I need to round down rather than up when its not a simple conversion.


Many thanks!

Answer

This is a simple function to calculate the fractions using only Math (no split) in vanilla Javascript.

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById("number").addEventListener("change", function(event) {
  var f = parseFloat(document.getElementById("number").value); // float
  var w = Math.floor(f); // whole number
  var r = f - w; // remainder
  var d = Math.floor(r / .125); // denominator

  document.getElementById("results").innerHTML = f + " as a fraction: " + w + ' ' + d + '/8<br>' + document.getElementById("results").innerHTML;
})});
Enter a number to convert to fractions of 1/8s.<br>
<input type="text" id="number" name="number" />
<div id="results"></div>