--- title: Rational Approximation hide_table_of_contents: true ---
The SheetJS `frac` library computes rational approximations to floating point numbers with bounded denominator. It is a core component in number formatting, powering "Fraction with up to 1 digit" and related number formats. The library is also available for standalone use on the SheetJS CDN[^1]. Source code and project documentation are hosted on the SheetJS git server at https://git.sheetjs.com/sheetjs/frac ## Live Demo The formatted text is calculated from the specified number format and value. Please [report an issue](https://git.sheetjs.com/sheetjs/frac/issues) if a particular format is not supported. ```jsx live function SheetJSFrac() { const [val, setVal] = React.useState(0.6994); const [text, setText] = React.useState(""); if(typeof frac == "undefined") return ( ERROR: Reload this page ); const fmt = arr => `${(""+arr[1]).padStart(3)} / ${(""+arr[2]).padEnd(3)}`; React.useEffect(() => { if(typeof frac == "undefined") return setText("ERROR: Reload this page!"); let v = +val; if(!isFinite(v)) return setText(`ERROR: ${val} is not a valid number!`); try { fmt(frac(val, 9)); setText(""); } catch(e) { setText("ERROR: " + (e && e.message || e)); } }, [val]); const g = { backgroundColor:"#C6EFCE", color:"#006100", whiteSpace:"pre-wrap" }; const b = { backgroundColor:"#FFC7CE", color:"#9C0006" }; return (Number Value | setVal(e.target.value)}/> | |
Mediant | Cont | |
---|---|---|
Up to 1 Digit | {text||fmt(frac(val,9))} |
{text||fmt(frac.cont(val,9))} |
Up to 2 Digits | {text||fmt(frac(val,99))} |
{text||fmt(frac.cont(val,99))} |
Up to 3 Digits | {text||fmt(frac(val,999))} |
{text||fmt(frac.cont(val,999))} |