[Question]
  [
Take the decimal number \$0.70710678\$. As a fraction, it'd be \$\frac{70710678}{100000000}\$, which simplifies to \$\frac{35355339}{50000000}\$. If you were to make the denominator \$1\$, the closest fraction is \$\frac{1}{1}\$. With \$2\$, it'd be \$\frac{1}{2}\$, and with \$3\$ it's \$\frac{2}{3}\$. Because \$0.\bar{6}\$ is closer to \$0.70710678\$ than \$\frac{3}{4}\$ or \$\frac{4}{5}\$, it would still be the closest with a maximum denominator up to (and including) \$6\$.
### Task
There are two inputs: a decimal, and a maximum denominator.
The first input consists of a number \$n\$ as input, where \$0\le n<1\$, and the fractional part is represented with a decimal (although not necessarily using base 10). This can be represented as a floating point number, an integer representing a multiple of \$10^{-8}\$ (or some other sufficiently smaller number), a string representation of the number, or any other reasonable format.
The second input is an integer \$n\ge1\$, also taken in any reasonable format.
The output should be a fraction, with a denominator \$d\le n\$, where \$n\$ is the second input. This should be the closest fraction to the inputted decimal that is possible with the restrictions placed on the denominator. If there are multiple which are equally close (or equal to the inputted number), the one with the smallest denominator should be chosen. If there are two with the same denominator which are equidistant, either are acceptable.
The outputted fraction can be represented in any reasonable format, as long as it consists of a numerator and denominator, both being natural numbers.
### Test cases
```
0.7         4   ->   2 / 3
0.25285     15  ->   1 / 4
0.1         10  ->   1 / 10
0.1         5   ->   0 / 1
0.68888889  60  ->  31 / 45
0.68888889  30  ->  20 / 29
0.0         2   ->   0 / 1
0.99999999  99  ->   1 / 1
```
### Other
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes per language wins!
  
[Answer]
# Scratch 3.0, 45 blocks/254 bytes
[![enter image description here](https://i.stack.imgur.com/1CwIR.png)](https://i.stack.imgur.com/1CwIR.png)
As SB Syntax:
```
define(n)(d)
set[A v]to(0
set[D v]to(d
set[i v]to(0
repeat((n)+(1
set[j v]to(0
repeat((n)+(1
set[r v]to((i)/(j
if<(D)>([abs v]of((r)-(D)))>then
set[A v]to(join(i)(join(/)(j
set[D v]to([abs v]of((r)-(D
end
set[j v]to((j)+(1
end
set[i v]to((i)+(1
end
say(A
```
[Try it on Scratch!](https://scratch.mit.edu/projects/506339261/)
Just wouldn't be right if I didn't do this in Scratch.
## Explained
```
define(n)(d) // Define an empty name function with parameters `n` (the denominator) and `d` (the decimal to fractionify)
set[D v]to(d // This will store the current absolute difference between potential fraction and actual decimal
set[i v]to(0 // outer-cartesian-loop variable
repeat((n)+(1
set[j v]to(0 // inner-cartesian-loop variable
repeat((n)+(1 // simulate cartesian product of range(0, n+1) and range(0, n+1)
set[r v]to((i)/(j // divide i / j
if<(D)>([abs v]of((r)-(D)))>then // if the difference between (i/j) and d is smaller than the current smallest difference
set[A v]to(join(i)(join(/)(j // update answer and difference
set[D v]to([abs v]of((r)-(D
end
set[j v]to((j)+(1
end
set[i v]to((i)+(1
end
say(A // output answer
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 10 bytes
```
◄oa-⁰´×/ŀ→
```
[Try it online!](https://tio.run/##ASIA3f9odXNr///il4RvYS3igbDCtMOXL8WA4oaS////MC4x/zEw "Husk – Try It Online")
`≠` is absolute difference, but doesn't seem to work for floats. So `oa-` is used.
-2 bytes from Leo.
## Explanation
```
◄oa-⁰´×/ŀ→ Inputs: decimal → ⁰, max denominator → implicit
        ŀ→ range 0..denominator
     ´×/   convert all possible pairs to fractions
◄o         min by
  a-⁰      absolute difference with the decimal
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ÝD¦âΣ`/α}¬
```
[Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//8OdRMKmw6LOo2AvzrF9wqz//zE1CjAuMjUyODU "05AB1E – Try It Online")
## Explanation
```
Ý          # [0 .. input]
 D         # Duplicate
  ¦        # Tail -> [1 .. input]
   â       # Cartesian product
    Σ   }  # Sort by
       α   # Absolute difference between
           # Input 2
     `/    # and numerator / denominator
         ¬ # Head
```
[Answer]
# [J](http://jsoftware.com/), 21 bytes
```
(0{]/:&,|@-)%/~@i.@>:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQyqY/Wt1HRqHHQ1VfXrHDL1HOys/mtypSZn5CsYFRkr2CoY6JkrpCmYVEDEDItMwGJGpkYWpgpACUNTuIyhAVjKECRqABVFCMHUGQONMAWLmlmAgSXIGDOYBiODIiNLDGljVPMMgEJGMHvBIpZQAJSwtKz4DwA "J – Try It Online")
Takes float as left input, max denominator as right input.
* `%/~@i.@>:` Creates "division table" for all pairs 0 to max denominator.
* `|@-` Elementwise differences between those table values and the target float.
* `]/:&,` Sort the table `/:` according to those differences after flattening both `&,`.
* `0{` Return the first item in the sorted list.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Żpḷ÷/ạ¥ÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8///o7oKHO7Yf3q7/cNfCQ0sPz3u4Y9H////NDP4b6JlZgIElAA "Jelly – Try It Online")
[Verify all test cases](https://tio.run/##y0rNyan8///o7oKHO7Yf3q7/cNfCQ0sPz3u4Y9H/w8sd9B81rfn/PzraQM9cxyRWhwvIMDI1sjDVMTSF8Ax1DA1gLKiQmQUYWOqYGaAJGEMFDHSMIAxLKNCxtIyNBQA "Jelly – Try It Online")
Note that this selects the fraction with the smallest *numerator*, and I'm not completely sure if it's always also the one with the smallest denominator.
Takes the maximum denominator as the first argument and the float as the second argument.
## Explanation
```
Żpḷ÷/ạ¥ÞḢ   Main dyadic link, taking m and x
Ż           Range [0..m]
 p          Cartesian product with
  ḷ         m, implicitly converted to the range [1..m]
       Þ    Sort by
      ¥     (
   ÷/         Divide the two numbers
     ạ        Absolute difference with x
      ¥     )
        Ḣ   Head
```
[Answer]
# JavaScript (ES7), 64 bytes
Expects `(value)(max_denominator)`. Returns `[numerator, denominator]`.
```
v=>g=(d,e)=>d?g(d-1,(E=((q=v*d+.5|0)/d-v)**2)>e?e:(r=[q,d],E)):r
```
[Try it online!](https://tio.run/##fc89D4IwEAbg3V/R8Q75aAtVMClOzCauxsHQQjQGFE0n/zvyIQQl8ZKmNzzXe3s5mdMjrc63p1OUSteZrI2McwnK1ihjtc1BOcyGRALcpbHU0hUvip5yDFoWx1hv9QYqebjb6mgniJuqTsviUV61ey1zyIC6a9IXQkAQiec1PSce8Re/kgseik4yMUjWyGAm2fgmo1PJ6B8qxvW0pc292/djYja1CruKEFbDAr@L8o/6A@XtAh7NKB2z8O8sMxl9CqE50w/Wbw "JavaScript (Node.js) – Try It Online")
### Commented
```
v =>                     // outer function taking the float value v
g = (d, e) =>            // inner recursive function taking the maximum denominator d
                         // and the current minimum error e, initially undefined
  d ?                    // if d is not equal to 0:
    g(                   //   do a recursive call:
      d - 1, (           //     decrement d
        E = (            //     compute the new error E = (q / d - v)²
          (q = v * d     //     where q is round(v * d)
               + .5 | 0) //
          / d - v        //
        ) ** 2           //     it's shorter to square than to use Math.abs()
      )                  //
      > e ?              //     if E is greater than e (always false if e is still
                         //     undefined):
        e                //       pass e unchanged
      :                  //     else:
        (r = [q, d], E)  //       save the new result [q, d] in r and pass E
    )                    //   end of recursive call
  :                      // else:
    r                    //   return the final result
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~97~~ 90 bytes
```
def f(n,k,a=[1]):
 while k:p=round(n*k);j=abs(p/k-n);a=[a,(j,p,k)][j<=a[0]];k-=1
 return a
```
[Try it online!](https://tio.run/##XY/LDoIwEEX3fsXEVWsGLSDIw/ojpIsaIUDN0FSI8euxCnHhXZ05ucnk2tfYDhTP861uoGGEBrWsQsWLDTzb7l6DKax0w0Q3RjvDy17q64PZgwmIl76qkfVo0XBV9WepK6FUaQIZbsDV4@QI9NwMDgjBQEdQMbE/IRw5gqcoibIEIUyWM/QofrjKNPsmx1T8iXgVAiFaKF@Dec6VX@BjXUcj@7xH2AaXLS4rOZ/f "Python 3 – Try It Online")
`round(n*k)` gets the closest numerator for a given denominator `k`.
`abs(p/k-n)` calculates the absolute value between this fraction and the input fraction `n`. If this is the best option so far, then update the answer accordingly.
Outputs three values: the absolute difference, the numerator and the denominator respectively.
*thanks to Noodle9 for -7 bytes*
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 83 bytes
```
param($n,$d)1..$d|%{0..($x=$_)|%{@{n=$_;d=$x}}}|sort{[Math]::Abs($_.n/$_.d-$n)}-t 1
```
[Try it online!](https://tio.run/##XZBNa4NAEIbP9Vd4mBaXbjZqaxojC5aUQg9tCj2KiMluSIuusrvSgNnfbtWaUDqH4X2fGZiPuvrmUh14UXSwp21X5zIvHRAYGPIIAXa6bl1CHDhSyFBv4lb0KmIUjsaYk6qkbpPXXB/S1epxqxzIiJj3ic1AIDPTttcZCzRXep0rrmjsWLHjkgd8j/Co/MBfBtgLJuthz73IM1wsxwjxwv1P7s7Exf6kwilwGCILWSC5ago9jEZ/Nulvsa5A2tS@gb0dZ4P5bbylyfvHulG6KjfbL77TabKRjEvO0rh9EXWjhw@8NSWXua4kBUlE9MRFVXJxBix6lvlOf1ZiLM8HZCxzWab7AQ "PowerShell – Try It Online")
[Answer]
# Excel, 72 bytes
```
=LET(a,SEQUENCE(B1),x,ROUND(A1*a,),INDEX(SORTBY(x&"/"&a,ABS(x/a-A1)),1))
```
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), ~~62~~ 57 bytes
-3 bytes thanks to [J42161217](https://codegolf.stackexchange.com/users/67961/j42161217).
```
MinimalBy[Join@@Array[Divide,{#,#}+1,0],a|->Abs[a-#2],1]&
```
[Try it online!](https://tio.run/##XYg9CsIwGEB3r1Fw8dP8aGszCKk4CYK6hgxRUwy0taSxUEou4Q08oUeoaOvim957uXJXnStnzqpLV93OFCZX2boR25spOE@sVY3YmNpcNLQBBH5CAEtQr8czOVVCTQMqgchxt7emcIgnZZk1IpWIH3WtbaURb0ctni1h4eEjNKRxCCTsiwDBPxtWFH9hEOG/MR8GBtoLGwDGvEfocDfadW8 "Wolfram Language (Mathematica) – Try It Online")
(uses [\[Function]](http://reference.wolfram.com/language/ref/character/Function.html) rather than `|->`, as TIO doesn't have the most recent version of the language)
Does the brute-force method of generating every possible fraction and taking the one closest to the given number. I previously had a solution using [Convergents](http://reference.wolfram.com/language/ref/Convergents.html), but it failed for inputs like `0.1` where, because of the language accounting for inexact numbers, the closest fraction wouldn't appear in the list.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 69 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.625 bytes
```
ʁ:ḢẊµƒ/⁰ε;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiyoE64bii4bqKwrXGki/igbDOtTtoIiwiIiwiNVxuMC4xIl0=)
A port of the 05AB1E answer updated to 2.6+ and vyncoded.
## Explained
```
ʁ:ḢẊµƒ/⁰ε;h
ʁ:         # Push two copies of the range [0, input)
  Ḣ        # on one of those copies, remove the first element
   Ẋ       # Take the cartesian product of these two lists
    µ...;  # And sort this by:
     ƒ/⁰ε  # the absolute difference between the second input and the item reduced by division
         h # output the first item
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 81 bytes
```
n=>k=>eval('for(a=0,b=M=1;b<=k;(m=a/b<n?n-a++/b:a/b++-n)<M&&[R=P,M=m])P=[a,b];R')
```
[Try it online!](https://tio.run/##dcrRCoJAEAXQ9z5EZ1jN1dI0HfsCQXwVH3YlwcxNTPz9TSKIDbpwH@bcuYlVPNu5nxZ3jXVHWlE@UH5dxR3s7jGDIO5IKshPZUZDCiMJT2bqolzBmCfP28WYqzArLKuuqHQKGhssqRaObNLKRj3NvVqgA74/IRwRd18IwiAOEfzQUH8T/ivmSxS/kyBE/M9wMAeOEBiQfIKwFfUL "JavaScript (V8) – Try It Online")
Maybe there are edge cases which failed due to floating point errors. But it at least pass all testcases given by OP.
[Answer]
# JavaScript (ES6), 63 bytes
```
c=>f=(d,M)=>d?f(d-1,M>(N=(.5-d*c%1)**2)?M:(s=d,N)):[c*s+.5|0,s]
```
Like [this](https://codegolf.stackexchange.com/a/221220/83717) answer, expects `(value)(max_denominator)`, and returns `[numerator, denominator]`.
Here's how it works:
```
c=>                          // the decimal - this will not change
  f=(                        // the inner recursive function
    d,                       // the max denominator. We will decrement this to loop
    M                        // the "error" (with a twist)
  )=>                        
    d?                       // if d is nonzero, we're still recursing
      f(d-1,                 // call f with the new denominator we're testing
        M>                   // the bigger M is, the closer d*c is to an integer
          (N=                // we'll test the error and save it in N in case we need it
            (.5-d*c%1)**2    // the error (with the twist); the closer d*c to an integer, the
                             // closer d*c%1 to 0 or 1, the closer .5-d*c%1 to .5, the bigger
                             // (.5-d*c%1)**2 is. This means; bigger "error" is better
          )
          ?M                 // if M is bigger than the newly checked error, continue with M
          :(                 // otherwise,
            s=d,             // save that denominator in s,
            N                // continue with the new error (that we saved in N)
          )
        )
    :                        // if d is zero, we've checked all denominators so we're done
    [c*s+.5|0,               // return the numerator (which is just c*s rounded to the nearest integer)
    s]                       // and the denominator, which we saved in s
```
[Answer]
# [R](https://www.r-project.org/), 61 bytes
```
function(n,d,a=round(n*1:d))c(a[i<-which.min((a/1:d-n)^2)],i)
```
[Try it online!](https://tio.run/##jc/RCoMgFAbg@57iwG50WKnNlmPtRcY2pIi8mIUstrdvJRHSInaulPP582t71ba2@Twqq4qXbkzeV51xJ2RISVRum86UyOzZqcS4QOqqz@G71kUdPbVBSMXDIjT4zvGNaLyMQzQ6EpjmABhgBxBehguHGJLgl3PBM@GeMOFxNvDDCmdzOqMLzuimF34bOvoVnmZuJIHUi09cG7HpE8/zMZ7LFU/nOvyfOnIaAlIufxv0Xw "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
ＮθＦＮＦ⁺²ι⊞υ⟦↔⁻∕κ⊕ιθκ⊕ι⟧Ｉ✂⌊υ¹
```
[Try it online!](https://tio.run/##ZY09C8IwFEX3/oqMLxDFFgpCJ9Glg1JwFIc2jfTRfNgkr38/xk6Cyx3O5dwrp95L1@uUWvumeCMzKA8Lb4qX8wx@IedsY52mAJVgmEFHYQIS7HEagtMUFVzR5vqCK44KZsFaK70yykY1QjYEW77xVzzzY@fRRjj3IcJdo9y20JABykbJeZPSYV/V1bEuyjrtVv0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Ｎθ
```
Input `n`.
```
ＦＮ
```
Input the maximum denominator and loop up to it. (The actual denominator is 1 more than the loop index.)
```
Ｆ⁺²ι
```
Loop over the possible numerators.
```
⊞υ⟦↔⁻∕κ⊕ιθκ⊕ι⟧
```
Calculate the error and save the numerator and denominator with it.
```
Ｉ✂⌊υ¹
```
Output the numerator and denominator with the smallest error (in the case of a tie, the smallest numerator wins).
[Answer]
# [JavaScript (V8)](https://v8.dev/), 93 bytes
```
(d,m)=>eval("for(i=1,b=m;i<=m;i++)n=Math.round(d*i),w=Math.abs(d-n/i),w<b?[b=w,x=[n,i]]:0;x")
```
[Try it online!](https://tio.run/##dcpBDoIwFATQvadoWLXywYKCVKiewBMQFq1IrJFCAIHbo6iJqYmzmMWbuYpetKdG1Z3TR1PBJ5xDSfj@3IsbtoqqwYp7IHkZq2Qu2yaaH0V3cZvqrnOcLxWB4S1Ctjh39GqWRB5SyQcYeapBZdmOxqNFprpRusMFpu4W0IaQxRf8wI8CQF5gqPcU@ivmJYxeYYBC@mdYmwMF5BvAPgHEGCHTAw "JavaScript (V8) – Try It Online")
**Explanation:**
Fairly straighforward approach. Most of the work is done by a `for` loop, wrapped in an `eval` statement. This saves bytes, as it's shorter than wrapping it in `{}` (which requires `return`).
During the `for` loop (all iterations are denominators from `1` to `m`), four things happen:
* `n` is set to the closest numerator
* `w` is set to the distance between the fraction and the `d` (the first number)
* `w` is compared with the previous best, `b` (initially `Infinity`)
* If `w` is less than `b`, `b` takes `w`'s value and `x` (the output) becomes the outputted fraction
[Answer]
# [Haskell](https://www.haskell.org/), 100 bytes
```
u=10^8
a#b|b!!0<a!!0=b|1>0=a
n!m=tail$foldl1(#)[[min o$u-o,div(n*d+o)u,d]|d<-[1..m],let o=n*d`mod`u]
```
[Try it online!](https://tio.run/##bdBLU4MwEADge3/F9nEAu8WER1uc0l@gJ4@IlhqcdiShY0F74L/jEh5Spzskmdkvu7PhEJ8/kzStqiLg7HU9iqf7cj8es01MW7Av@ZYF8UiNZZDHx3T2kaUi5cbUDEN5VJDNikWG4vhtqDsxz8wCRVSKzSLkliUjTJMcsoBoJzOxK6JKxlQUgIxPT29wKvLn/OtRQQjnQ/YDCuZzmCBM6lNnZHzROQi2g6wBNA6Jqe1FQXI5Je95IuBhcEsVsqm9HyRFotqiyQgoSkMhtUK6jGQmTa7zYKxYEwgugo3gmNiK7dlrTwv3kJP3wvsazmrh7AZ5CPWFXpZrHT7CkqHD0fVukMPQps/vCZpgera6H/Tkt4FAi2uKoopZK@jCpbXY0mbTz3FGzNJP0sS9ljiRS8T7Ks4GxNmVeV1HVhtRNzrQqxpydEfvypzW7LrM9slY39L@37J7F0C9/ib5BQ "Haskell – Try It Online")
* input as 8 digits of the decimal part of n.
* output a [ numerator, denominator ] list.
a#b selects a or b (which are [distance to closest 10^8 multiple, numerator , denominator] ) based on minimum distance.
n!m computes every [dist, num, den] from 1 to m ,  
then finds closest fraction folding by # and return only [num,den]
[Answer]
# [Julia 1.7](https://julialang.org), 37 bytes
```
x|n=argmin(y->(x-y)^2,(0:n).//(1:n)')
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZDRCoIwGIXpdk_x30QTUreZpYOCnkMMpFYYNkInKPgm3XTTQ9XTtDY16odx-PftHMa5Pc51kWf3-6NWRzd6TptOrrPydMklbt0NbtzW2bE5Jlw6nu9jqnXm2MevyUyJSlWwhq1sE0S8FQyzsMLA9yHQhIUsCs0V7eVDFprQ0UPJl1Dyg6wHiEGaLCMzMcDSmAIbF_6gwCBmTCzWiIx57C8v7gfgc8ZPoBShQ15di6zFCW-AS-CiuYq9EgfgpajqQgGyJWAjCZ_TFLwOho2lTtr3NZT8Bg)
`argmin(f, domain)` needs julia 1.7 or later
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `h`, 10 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
LDḣṖÞẸ/¹-A
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0UoZS7IKlpSVpuhabfFwe7lj8cOe0w_Me7tqhf2inruOS4qTkYqj0gqWmXAZ6hhAOAA)
Port of user100947's 05AB1E answer.
#### Explanation
```
LDḣṖÞẸ/¹-A  # Implicit input
LD          # Push [0..input) and duplicate
  ḣṖ        # Cartesian product of [0..input) with [1..input)
    Þ       # Sort by:
     Ẹ/     #  Dump and divide
       ¹-A  #  Absolute difference with second input
            # Implicit output of first item
```
]