Q:

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!

A:

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 a = Math.abs(f); // absolute value
  var w = Math.floor(a); // whole number
  var r = a - w; // remainder
  var d = Math.floor(r / .125); // denominator

  document.getElementById("results").innerHTML = f + " as a fraction: " + (f < 0 ? '-' : '') + w + ' ' + (d > 0 ? 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>

