require "liquid" require "jekyll" module Jekyll module FractionaliseFilter def fractionalise(input) input = input.to_s if not input.include? "." # if input is a whole number, just return it return input end if input.split(".").length != 2 # generally when liquid filters fail they just print nothing, so we'll do that too return "" end leading_integer, decimal = input.split(".") decimal = "0.#{decimal}" rational = case decimal # handle common weird cases so that e.g. 0.3 returns "1/3" and not "3/10" or "5404319552844595/18014398509481984" when "0.3", "0.33", "0.333" Rational(1, 3) when "0.6", "0.67", "0.666" Rational(2, 3) else decimal.to_r end "#{leading_integer != "0" ? "#{leading_integer} " : ""}#{rational.numerator}#{rational.denominator}" end end end Liquid::Template.register_filter(Jekyll::FractionaliseFilter)