<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bogdan Umaniuk on Medium]]></title>
        <description><![CDATA[Stories by Bogdan Umaniuk on Medium]]></description>
        <link>https://medium.com/@umaniukbogdan?source=rss-dee42f95b39f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UNykn1gM9K0cntUN</url>
            <title>Stories by Bogdan Umaniuk on Medium</title>
            <link>https://medium.com/@umaniukbogdan?source=rss-dee42f95b39f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 13:17:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umaniukbogdan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I wrote MobX from scratch in 150 lines. Here’s every bug I hit]]></title>
            <link>https://medium.com/@umaniukbogdan/i-wrote-mobx-from-scratch-in-150-lines-heres-every-bug-i-hit-e5765ea20754?source=rss-dee42f95b39f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5765ea20754</guid>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Bogdan Umaniuk]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 22:43:18 GMT</pubDate>
            <atom:updated>2026-10-29T22:43:18.034Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m preparing for senior React Native interviews, and one kind of task keeps showing up: “write your own state manager”. Redux is the usual target. I picked MobX instead, because I’ve used it for years and realized I couldn’t explain what happens between store.count++ and the re-render.</p><p>The finished version is about 150 lines: observable, autorun, computed, action, and a React hook. Getting there took a lot more than 150 lines of wrong code. This post goes through the bugs in the order I made them. Every output below comes from running the code.</p><h3>The core: track on read, trigger on write</h3><p>MobX doesn’t ask you to declare dependencies. A reaction runs once, MobX watches which fields it reads, and from then on it reruns only when one of those fields changes.</p><p>You need two pieces for that. A global variable that says which reaction is running right now, and a Proxy that records reads and announces writes:</p><pre>type Reaction = (() =&gt; void) &amp; { deps: Set&lt;Set&lt;Reaction&gt;&gt; }<br> <br>let currentReaction: Reaction | null = null<br> <br>export const observable = &lt;T extends object&gt;(object: T): T =&gt; {<br>  const reactionsByKey = new Map&lt;string | symbol, Set&lt;Reaction&gt;&gt;()<br> <br>  const track = (key: string | symbol) =&gt; {<br>    if (!currentReaction) return<br>    let reactions = reactionsByKey.get(key)<br>    if (!reactions) {<br>      reactions = new Set()<br>      reactionsByKey.set(key, reactions)<br>    }<br>    reactions.add(currentReaction)<br>    currentReaction.deps.add(reactions)<br>  }<br> <br>  const trigger = (key: string | symbol) =&gt; {<br>    const reactions = reactionsByKey.get(key)<br>    if (!reactions) return<br>    [...reactions].forEach((reaction) =&gt; reaction())<br>  }<br> <br>  return new Proxy(object, {<br>    get(obj, key, receiver) {<br>      track(key)<br>      return Reflect.get(obj, key, receiver)<br>    },<br>    set(obj, key, value, receiver) {<br>      if (Object.is(Reflect.get(obj, key, receiver), value)) return true<br>      const result = Reflect.set(obj, key, value, receiver)<br>      if (result) trigger(key)<br>      return result<br>    },<br>  })<br>}</pre><p>Every key has a Set of reactions that read it. autorun puts itself into currentReaction, calls your function, and every get along the way adds it to the right Sets.</p><p>A few Proxy details matter here. The set trap has to return true, because a falsy result throws a TypeError in strict mode. Reflect.set already returns a boolean, so passing it through is enough. Object.is skips writes that don&#39;t change anything, and unlike === it treats NaN as equal to NaN, so writing NaN over NaN doesn&#39;t wake anyone up. The receiver argument decides what this is inside getters and setters on the object. It confused me enough that it gets its own post.</p><p>Almost every line above was a bug fix at some point.</p><h3>Bug 1: a reaction that listens to fields it stopped reading</h3><p>My first autorun just set currentReaction, called the function and cleared it. Dependencies only ever got added. Here&#39;s what that does to a conditional read:</p><pre>const s = observable({ show: true, name: &#39;Bogdan&#39; })<br> <br>autorun(() =&gt; console.log(&#39;render:&#39;, s.show ? s.name : &#39;hidden&#39;))<br> <br>s.show = false<br>s.name = &#39;Ivan&#39;</pre><pre>render: Bogdan<br>render: hidden<br>render: hidden</pre><p>After show became false, the function no longer read name. It still reran when name changed, because it was still sitting in the Set for name from the first run. In a React app this is a component that re-renders because of data it doesn&#39;t display.</p><p>Dependencies have to be rebuilt on every run. Before calling the function, remove the reaction from every Set it’s in, and let the run add it back where it still belongs. That’s why each reaction keeps deps, a Set of the Sets that contain it. Without the link back, there&#39;s no way to find those Sets:</p><pre>const cleanup = () =&gt; {<br>  reaction.deps.forEach((set) =&gt; set.delete(reaction))<br>  reaction.deps.clear()<br>}</pre><p>With cleanup the same code prints two lines.</p><h3>Bug 2: the Set that never ends</h3><p>Cleanup fixed bug 1 and broke something else. My trigger iterated the Set directly:</p><pre>reactions.forEach((reaction) =&gt; reaction())</pre><pre>const s = observable({ count: 0 })<br>autorun(() =&gt; console.log(&#39;count:&#39;, s.count))<br>s.count = 1</pre><pre>count: 0<br>count: 1<br>count: 1<br>count: 1<br>count: 1<br>...</pre><p>It never stopped. I had a guard that threw after a few runs, otherwise the tab would just hang.</p><p>Set.prototype.forEach visits entries that are added while it&#39;s iterating. If you delete an entry and add it back, it goes to the end of the Set and gets visited again. That&#39;s exactly what a reaction does: cleanup deletes it from the Set for count, then the function reads count and track adds it back. forEach sees a &quot;new&quot; entry and calls it, and the same thing happens again.</p><p>You can see it without any reactivity:</p><pre>const set = new Set([&#39;x&#39;])<br>let visits = 0<br>set.forEach((v) =&gt; {<br>  if (++visits &gt; 3) return<br>  set.delete(v)<br>  set.add(v)<br>})<br>visits // 4</pre><p>The fix is to iterate over a copy, [...reactions]. Vue 3 copied the Set in triggerEffects in the same way, until 3.5 replaced Sets with linked lists. I hit this bug a second time later, when I wrote batching.</p><h3>Bug 3: a nested autorun steals tracking from its parent</h3><p>If an autorun creates another autorun, the inner one overwrites currentReaction. When it finishes and resets it to null, the outer one keeps running with no reaction to attach reads to:</p><pre>const s = observable({ a: 1, c: 1 })<br> <br>autorun(() =&gt; {<br>  autorun(() =&gt; console.log(&#39;inner a:&#39;, s.a))<br>  console.log(&#39;outer c:&#39;, s.c)<br>})<br> <br>s.c = 2</pre><p>Nothing happens on s.c = 2. The outer reaction read c while currentReaction was null, so it never subscribed.</p><p>The fix is a stack, but you don’t need an array for it. Each run remembers the previous reaction and puts it back at the end, in finally so that an exception in the function doesn&#39;t leave the wrong reaction behind:</p><pre>const previousReaction = currentReaction<br>try {<br>  currentReaction = reaction<br>  cleanup()<br>  fn()<br>} finally {<br>  currentReaction = previousReaction<br>}</pre><p>After this change, s.c = 2 prints outer c: 2.</p><h3>Bug 4: dispose that didn’t dispose</h3><p>autorun returns a function that stops it. It needs two things: cleanup() to remove the reaction from all Sets, and an isDisposed flag. The flag covers the case where trigger already copied the Set and the reaction is in that copy when it gets disposed. Without the flag, it would run one more time after you stopped it.</p><p>Later I moved the shared code into a helper and passed the flag as an argument:</p><pre>const makeReaction = (isDisposed: boolean, fn: () =&gt; void) =&gt; {<br>  const reaction = () =&gt; {<br>    if (isDisposed) return<br>    // ...<br>  }<br>}<br> <br>export const autorun = (fn: () =&gt; void) =&gt; {<br>  let isDisposed = false<br>  const reaction = makeReaction(isDisposed, fn)<br>  // ...<br>  return () =&gt; { isDisposed = true }<br>}</pre><p>A boolean is passed by value. isDisposed = true in dispose changes the variable in autorun, and the helper still has its own false. The check has to read the variable through a closure, either by keeping it in the scope where the reaction is created or by passing a getter.</p><h3>Hooking it up to React</h3><p>The first hook was useState plus useEffect: run an autorun in an effect and push the selected value into state. Two things went wrong.</p><p>I wrote setState(value). When the selected value is a function, React calls it as an updater instead of storing it. The safe form is setState(() =&gt; value).</p><p>The selector you pass changes on every render, because it’s usually an inline arrow. The autorun is created once, so it would keep calling the selector from the first render. The latest selector goes into a ref, updated in useLayoutEffect, and the autorun reads selector.current.</p><p>The second version uses useSyncExternalStore, which React 18 added for exactly this, and which avoids tearing in concurrent rendering:</p><pre>export const useObserver = &lt;T,&gt;(fn: () =&gt; T) =&gt; {<br>  const selector = useRef(fn)<br> <br>  useLayoutEffect(() =&gt; {<br>    selector.current = fn<br>  }, [fn])<br> <br>  const subscribe = useCallback(<br>    (onStoreChange: () =&gt; void) =&gt;<br>      autorun(() =&gt; {<br>        selector.current()<br>        onStoreChange()<br>      }),<br>    []<br>  )<br> <br>  return useSyncExternalStore(subscribe, fn)<br>}</pre><p>subscribe has to be stable. If it&#39;s a new function on each render, React unsubscribes and subscribes again every time. The autorun calls selector.current() only to subscribe to whatever it reads, and onStoreChange tells React to call getSnapshot again.</p><p>There’s a known trap I left unsolved. If the selector returns a new object or array, for example store.items.filter(...), getSnapshot returns a new reference on every call. React warns that the result of getSnapshot should be cached and then re-renders in a loop. A real implementation memoizes the snapshot.</p><h3>computed: a cache that knows when it’s stale</h3><p>computed is a derived value that is lazy and cached:</p><pre>const total = computed(() =&gt; cart.price * cart.qty)<br> <br>total.get() // computes<br>total.get() // returns the cached value<br>cart.qty = 3 // marks it stale, doesn&#39;t recompute<br>total.get() // recomputes</pre><p>It should recompute only when a field it actually read has changed. Its function also has to be pure. It can only depend on observable fields. If it reads a plain variable or Date.now(), nothing will ever tell it the value changed.</p><h4>Bug 5: isDirty started as false</h4><p>My first get() was if (isDirty) { value = fn(); isDirty = false } with isDirty initialized to false. The first call returned undefined, and nothing ever set the flag to true. That one&#39;s easy to find.</p><h4>Bug 6: subscribing the function that computes</h4><p>Then I needed something to set isDirty = true when a dependency changed. I reused the autorun machinery: a reaction that runs fn with tracking, and get() calls it when the value is stale.</p><p>The problem is which function ends up in the Sets. During tracking, currentReaction was the evaluator itself. So when cart.qty changed, trigger called the evaluator directly, bypassing get() and its isDirty check:</p><pre>const total = computed(() =&gt; cart.price * cart.qty)<br>total.get()  // 200, evaluator calls: 1<br>cart.qty = 3 // evaluator calls: 2<br>total.get()  // 200</pre><p>The value was recomputed eagerly when nobody asked for it. The result was thrown away, because trigger ignores return values. isDirty stayed false, so get() kept returning 200 from then on.</p><p>A computed needs two separate things. One is what trigger calls, and for a computed that function only marks it stale:</p><pre>const markDirty = () =&gt; { isDirty = true }</pre><p>The other is the tracked run of fn that happens inside get(), with markDirty as the current reaction. That way the fields subscribe markDirty, and fn runs only when someone reads the value.</p><h4>Bug 7: two functions called fn</h4><p>At this point autorun and computed had the same block: save the previous reaction, set the current one, clean up, run, restore in finally. I moved it into a shared createReaction:</p><pre>const createReaction = (fn: () =&gt; void) =&gt; {<br>  const reaction = Object.assign(() =&gt; fn(), { deps: new Set() })<br>  const cleanup = () =&gt; { /* ... */ }<br>  const run = () =&gt; {<br>    const previousReaction = currentReaction<br>    try {<br>      currentReaction = reaction<br>      cleanup()<br>      return fn()<br>    } finally {<br>      currentReaction = previousReaction<br>    }<br>  }<br>  return { reaction, cleanup, run }<br>}</pre><p>Inside createReaction, fn is the reaction callback: markDirty for a computed, and for an autorun a callback that calls run(). The user&#39;s function lives in a different scope with the same name. So the computed&#39;s run() executed markDirty and returned undefined, and the autorun did callback → run → callback → run until Maximum call stack size exceeded.</p><p>The function to run has to come in as an argument:</p><pre>const run = &lt;T,&gt;(work: () =&gt; T): T =&gt; {<br>  const previousReaction = currentReaction<br>  try {<br>    currentReaction = reaction<br>    cleanup()<br>    return work()<br>  } finally {<br>    currentReaction = previousReaction<br>  }<br>}</pre><p>The computed calls run(fn) with its formula, the autorun calls run(fn) with its body, and the parameter of createReaction gets a name that can&#39;t be confused with either, like onTrigger.</p><p>The autorun’s callback calls run, which only exists after createReaction returns. This works:</p><pre>const callback = () =&gt; {<br>  if (isDisposed) return<br>  run(fn)<br>}<br>const { reaction, cleanup, run } = createReaction(callback)<br>reaction()</pre><p>A closure captures the variable, not its value. callback is created before run exists, but it isn&#39;t called until reaction() on the last line, and by then run is initialized. Calling callback() before the destructuring would throw &quot;Cannot access &#39;run&#39; before initialization&quot;.</p><h3>action: five ways batching broke</h3><p>Every write triggers reactions right away, so two writes run an autorun twice, and the first run sees a half-updated state:</p><pre>autorun(() =&gt; console.log(cart.price, cart.qty))<br>cart.price = 200 // 200 2<br>cart.qty = 5     // 200 5</pre><p>action should collect the writes and run each affected reaction once at the end. Values are still written immediately, so reading cart.price inside the action returns the new value. Only reactions wait.</p><h4>Bug 8: a queue of Sets</h4><p>My first version put the Set of reactions for each changed key into a queue. price and qty have separate Sets, and the same autorun is in both:</p><pre>autorun: 100 2<br>autorun: 200 5<br>autorun: 200 5</pre><p>The queue has to hold reactions. A Set&lt;Reaction&gt; deduplicates them on its own.</p><h4>Bug 9: the queue was never cleared</h4><p>The next action ran every reaction from the previous one again. clear() after the flush.</p><h4>Bug 10: a nested action ended the batch early</h4><pre>action(() =&gt; {<br>  action(() =&gt; { s.a = 2 })<br>  s.b = 2<br>})</pre><p>The inner action set isBatching = false when it finished, so s.b = 2 ran reactions immediately. Each action has to remember the previous state of the flag, restore it, and flush only if it was the outermost one. MobX uses a counter, globalState.inBatch, and runs reactions when it drops back to zero. A saved boolean does the same job.</p><h4>Bug 11: computed went stale inside an action</h4><pre>const total = computed(() =&gt; s.price * s.qty)<br>total.get()<br> <br>action(() =&gt; {<br>  s.qty = 3<br>  console.log(total.get())<br>})</pre><pre>total inside action: 200<br>total after action: 300</pre><p>I had put the batching check into trigger: during an action, queue every reaction instead of calling it. That included markDirty. The computed didn&#39;t learn it was stale until the action ended, so get() inside the action returned the old value.</p><p>A computed doesn’t need batching at all. Marking it stale is cheap and the recompute is lazy anyway. The question is where the decision belongs. You can teach trigger the difference between kinds of reactions, but then the Reaction type needs a flag. I moved the check into the autorun&#39;s callback instead, and trigger went back to calling everything:</p><pre>const callback = () =&gt; {<br>  if (isDisposed) return<br>  if (isBatching) {<br>    batchingDelayedReactions.add(reaction)<br>    return<br>  }<br>  run(fn)<br>}</pre><p>MobX is built the same way. When a value changes, it calls onBecomeStale_ on every observer. A computed reacts by propagating &quot;maybe changed&quot; to its own observers. A reaction calls schedule_(), which pushes it onto globalState.pendingReactions, and the list runs when the batch ends.</p><h4>Bug 12: flushing while still batching</h4><p>With the check inside the reaction, the next run of my tests printed nothing after the action. The flush loop called each queued reaction while isBatching was still true, and each one put itself back into the queue and returned. The flag has to be reset before the flush.</p><h4>Bug 13: an exception left the flag on</h4><p>If the function passed to action threw, the code after it never ran, isBatching stayed true, and from then on every write in the app was queued and never flushed. Restoring the flag and flushing go into finally. The flush runs over a copy of the queue, for the same reason as bug 2.</p><p>The final version:</p><pre>let isBatching = false<br>const batchingDelayedReactions = new Set&lt;Reaction&gt;()<br> <br>export const action = (fn: () =&gt; void) =&gt; {<br>  const previousBatching = isBatching<br>  isBatching = true<br> <br>  try {<br>    fn()<br>  } finally {<br>    isBatching = previousBatching<br>    if (!previousBatching) {<br>      const reactions = [...batchingDelayedReactions]<br>      batchingDelayedReactions.clear()<br>      reactions.forEach((reaction) =&gt; reaction())<br>    }<br>  }<br>}</pre><p>My tests cover four cases: two actions in a row, a nested action, a computed read inside an action, and an exception followed by a plain write. All four pass now. Before this version, each of them failed in a different way.</p><h3>What’s still missing</h3><p>One gap is visible right away:</p><pre>const total = computed(() =&gt; cart.price * cart.qty)<br>autorun(() =&gt; console.log(&#39;total:&#39;, total.get()))<br>cart.qty = 3</pre><p>This prints total: 200 once, and nothing after qty changes. Inside get() the current reaction is markDirty, so the autorun never subscribes to price or qty, and the computed has no observers of its own. To fix it, a computed has to act as an observable: track whoever calls get(), and notify them when it becomes stale.</p><p>Even with that fixed, MobX does a lot more. Its graph avoids glitches: when two computeds depend on the same field and an autorun reads both, the autorun runs once and never sees one updated and one stale. A computed with no observers stops listening to its own dependencies. There are observable Map and Set, async actions with flow, comparers, onBecomeObserved hooks, trace and spy. That&#39;s why the production build of MobX 7.1.3 is around 14.7 KB gzipped, against my 150 lines.</p><p>What I got out of it is that I now know where all of that comes from. In an interview, “MobX tracks reads through Proxy” is the short answer. The cleanup, the copy before iterating, the restore in finally, and the batching check in the reaction are what the follow-up questions are about.</p><p>Originally published at <a href="https://umaniuk.dev/writing/mobx-from-scratch">umaniuk.dev</a>.</p><p>New posts go to my Telegram channel first: <a href="https://t.me/umaniuk_dev">t.me/umaniuk_dev</a></p><p>Questions, or a senior mobile role you think I’d fit? Message me on Telegram: <a href="https://t.me/umaniukbogdan">@umaniukbogdan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5765ea20754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why 0.1 + 0.2 breaks wallets: money math in JavaScript and every other language]]></title>
            <link>https://medium.com/@umaniukbogdan/why-0-1-0-2-breaks-wallets-money-math-in-javascript-and-every-other-language-0cfb03e34158?source=rss-dee42f95b39f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cfb03e34158</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bogdan Umaniuk]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 15:08:23 GMT</pubDate>
            <atom:updated>2026-10-26T15:08:23.875Z</atom:updated>
            <content:encoded><![CDATA[<p>I work on the mobile app of a crypto exchange, in React Native and native Android. Most of the money bugs I’ve run into came from small rounding decisions in the client that looked harmless in code review and broke on real balances. The most common one involves the Max button.</p><h3>The Max button that says “insufficient funds”</h3><p>A user has 10.4567 USDT. The screen shows two decimals, so somebody writes:</p><pre>const shown = balance.toFixed(2) // &quot;10.46&quot;</pre><p>The user taps Max, the field fills with 10.46, and the server answers &quot;insufficient funds&quot;. They only have 10.4567.</p><p>toFixed rounds to the nearest value, and .4567 is closer to .46 than to .45. For anything a user can spend, that&#39;s the wrong direction. You need to round down:</p><pre>import BigNumber from &#39;bignumber.js&#39;<br> <br>new BigNumber(&#39;10.4567&#39;).decimalPlaces(2, BigNumber.ROUND_DOWN).toFixed(2) // &quot;10.45&quot;</pre><p>Even with the right rounding direction, the number you round is often already off, because of how floats store decimals.</p><h3>Why 0.1 + 0.2 isn’t 0.3</h3><pre>0.1 + 0.2   // 0.30000000000000004<br>0.07 * 100  // 7.000000000000001</pre><p>Computers store numbers in base 2. In base 2 you can only write fractions exactly when the denominator is a power of two: 0.5, 0.25, 0.125. Values like 0.1, 0.07 or 0.001 become infinite fractions, the same way 1/3 is 0.3333... in base 10. The machine cuts them off at 53 bits and keeps the nearest value it can store.</p><p>This is what actually sits in memory:</p><pre>0.001 → 0.001000000000000000020816682...<br>0.07  → 0.07000000000000000666133815...</pre><p>JavaScript prints 0.07 because that&#39;s the shortest decimal that maps back to the same stored value. The tail is still there. Multiply by 100 and the tail grows to 7.000000000000000666.... Near 7, a double can only represent values about 0.00000000000000089 apart, and the nearest one to that result is 7.000000000000000888.... That gets printed as 7.000000000000001.</p><p>In money code that tail shows up in a few predictable places.</p><h3>Five ways floats turn into money bugs</h3><h4>Converting to cents loses a cent</h4><pre>1.13 * 100              // 112.99999999999999<br>Math.floor(1.13 * 100)  // 112</pre><p>The user typed 1.13 and the app sent 1.12. Or a &quot;minimum amount is 1.13&quot; check fails on exactly 1.13.</p><h4>toFixed rounds the stored value, not the one you see</h4><pre>(1.005).toFixed(2) // &quot;1.00&quot;</pre><p>You’d expect 1.01. But 1.005 is stored as 1.00499999..., and toFixed rounds what&#39;s stored. The app shows one value and the backend, which uses decimals, calculates another.</p><h4>Sums drift</h4><pre>let total = 0<br>for (let i = 0; i &lt; 10; i++) total += 0.1<br>total        // 0.9999999999999999<br>total === 1  // false</pre><p>Ten fees of 0.1 don&#39;t add up to 1. A transaction history total stops matching the balance, and any check like &quot;parts must equal the whole&quot; fails.</p><h4>Crypto amounts don’t fit at all</h4><p>ETH has 18 decimals. One ether is 10^18 wei, which is already past the range where a double can hold whole numbers exactly:</p><pre>Number.isSafeInteger(1e18)           // false<br>parseFloat(&#39;1.123456789012345678&#39;)   // 1.1234567890123457</pre><p>parseFloat drops the last digits without any error. For token amounts that means the number you display, or worse, the number you send, is quietly different from the real one.</p><h4>JSON drops precision in transit</h4><p>If an API returns { &quot;amount&quot;: 0.1234567890123456789 }, the JSON parser on the client usually turns it into a double and cuts it. The backend kept the precision and the wire threw it away. This is why financial APIs send amounts as strings.</p><h3>A real one: a Max button that offers more than you have</h3><p>This one came from a P2P trading screen in an app I work on. The user sells crypto for fiat. The Max button worked like this:</p><ol><li>Take the crypto balance, multiply it by the price, round to 2 decimals. That’s the max fiat amount.</li><li>Take that fiat amount, divide it by the price, round to the crypto precision. That’s the crypto amount.</li></ol><p>The code already used BigNumber. The problem was its default rounding mode, ROUND_HALF_UP: step 1 sometimes rounds the fiat amount up, and step 2 converts that inflated amount back into crypto.</p><p>With a balance of 896.117400 and a price of 86.16:</p><pre>896.1174 × 86.16  = 77209.475184<br>rounded           = 77209.48     (up)<br>77209.48 / 86.16  = 896.117456   (more than the balance)</pre><p>I ran it on 20,000 random balances and prices:</p><pre>Crypto precision   Max is above the balance<br>----------------   ------------------------<br>2 decimals         0%<br>4 decimals         ~6%<br>6 decimals         ~50%<br>8 decimals         ~50%</pre><p>For coins with 6 or 8 decimals, the button picked a number larger than the balance about half the time. The form only checked that the crypto amount was greater than zero, so nothing on the client caught it. The amount was then sent with Number(values.amount), which turns it into a double right before the request. What happens next depends on the backend. Most likely the user gets &quot;insufficient funds&quot; when they submit the deal.</p><h3>Which way to round</h3><p>For money, rounding should always land on the side that can’t create a deficit.</p><p>Anything the user can spend or receive rounds down: available balance, Max, the payout amount. Anything the user pays rounds up: fees, the amount to charge.</p><p>Fees are where the second rule matters. Take a 0.1% fee and a currency with 2 decimals:</p><pre>transfer 0.5 USDT → fee = 0.0005<br>round down → 0.00</pre><p>That transfer is free. Split 1000 USDT into 2000 transfers of 0.5 and nobody pays anything. This is a known abuse pattern, and even without bad intent, losing a cent on millions of operations adds up.</p><p>Rounding up has its own problem: the fee on 0.5 becomes 0.01, which is 2%. That&#39;s why exchanges also set a minimum operation amount or a minimum fee.</p><h4>Max depends on where the fee comes from</h4><p>Same balance, 10.4567, 2 decimals, 0.1% fee.</p><p>If the fee is taken out of the amount, Max is the balance rounded down, 10.45. The fee is 0.01045, rounded up to 0.02, and the recipient gets 10.43.</p><p>If the fee is charged on top, Max has to satisfy amount + fee ≤ balance:</p><pre>Amount   Fee (2 decimals, up)   Total   Fits in 10.4567?<br>------   --------------------   -----   ----------------<br>10.45    0.02                   10.47   no<br>10.44    0.02                   10.46   no<br>10.43    0.02                   10.45   yes</pre><p>If the fee is kept with 8 decimals, as exchanges usually do:</p><pre>Amount   Fee (8 decimals)   Total      Fits?<br>------   ----------------   --------   -----<br>10.45    0.01045            10.46045   no<br>10.44    0.01044            10.45044   yes</pre><p>So the same balance gives four different Max values: 10.46 (the bug), 10.45, 10.44 or 10.43. Which one is right depends on rules the client doesn&#39;t own. The backend defines the fee model, the precision of amounts and the precision of fees. The client either mirrors those rules exactly or asks the backend for the max amount directly. I prefer the second option.</p><h3>Rounding up on a double has its own bug</h3><p>Rounding fees up sounds simple:</p><pre>const ceil2 = (x) =&gt; Math.ceil(x * 100) / 100</pre><p>But the fee on 70 at 0.1% should be exactly 0.07:</p><pre>70 * 0.001        // 0.07<br>0.07 * 100        // 7.000000000000001<br>Math.ceil(7.000000000000001) / 100 // 0.08</pre><pre>Amount   Expected fee   Math.ceil on a double<br>------   ------------   ---------------------<br>70       0.07           0.08<br>140      0.14           0.15<br>280      0.28           0.29<br>1100     1.10           1.11<br>1300     1.30           1.30</pre><p>The last row is fine because 1.3 * 100 happens to land exactly on 130. So the bug depends on the amount, which makes it hard to reproduce. Math.ceil does nothing wrong here; it rounds the tail it was given. The fix is to never put money into a double:</p><pre>const fee = (amount, rate) =&gt;<br>  new BigNumber(amount)<br>    .times(rate)<br>    .decimalPlaces(2, BigNumber.ROUND_UP)<br>    .toFixed(2)<br> <br>fee(&#39;70&#39;, &#39;0.001&#39;)    // &quot;0.07&quot;<br>fee(&#39;70.01&#39;, &#39;0.001&#39;) // &quot;0.08&quot;</pre><h3>It’s a double problem, in every language</h3><p>JavaScript’s number is an IEEE 754 double, the same format as the default float in almost every mainstream language:</p><pre># Python<br>0.1 + 0.2    # 0.30000000000000004<br>0.07 * 100   # 7.000000000000001</pre><pre># Ruby<br>0.1 + 0.2    # 0.30000000000000004<br>0.07 * 100   # 7.000000000000001</pre><pre>// Swift<br>0.1 + 0.2    // 0.30000000000000004<br>0.07 * 100   // 7.000000000000001</pre><p>Java and Kotlin Double, Go float64 and C# double use the same format. A backend in any of them will charge 0.08 instead of 0.07 if it rounds fees up on a double.</p><p>Mature financial backends avoid this by doing money math in decimal types:</p><pre>Language or layer         Type for money<br>-----------------------   ----------------------------------------------------------<br>Java / Kotlin             BigDecimal<br>Ruby                      BigDecimal<br>Python                    decimal.Decimal<br>C#                        decimal<br>Go                        shopspring/decimal, or integers in minor units<br>SQL                       NUMERIC / DECIMAL columns<br>JavaScript / TypeScript   bignumber.js, decimal.js, big.js, or BigInt in minor units</pre><p>Java’s BigDecimal is the standard tool for money in the language a lot of banking software is written in. So the server is often the safest part of the system. Precision usually gets lost at the edges: when the client does its own math, when amounts travel as JSON numbers, and when a form value goes through Number() right before a request.</p><h3>BigNumber or BigInt?</h3><h4>Who uses decimal libraries</h4><p>bignumber.js, decimal.js and big.js were all written by the same developer, Michael Mclaughlin. In the week of October 16–22, 2026, npm counted about 65 million downloads for decimal.js, 42 million for bignumber.js and 20 million for big.js.</p><p>Several crypto SDKs depend on them. xrpl.js, the XRP Ledger SDK, and @stellar/stellar-base depend on bignumber.js. Aave&#39;s @aave/math-utils expects it as a peer dependency, and @0x/utils ships with it. Uniswap&#39;s @uniswap/sdk-core uses big.js together with JSBI. On the banking side, the same job is done by BigDecimal in Java and Kotlin backends, and fintech front ends commonly reach for one of these libraries once rates or percentages are involved.</p><p>They’re used because they do decimal arithmetic with a precision and a rounding mode you set yourself. Fees and exchange rates need division, and division needs a rounding rule.</p><h4>Why BigInt alone doesn’t fit</h4><p>BigInt is built into the language and handles arbitrarily large integers exactly, but only integers:</p><pre>BigInt(0.07)    // RangeError: not an integer<br>BigInt(&#39;0.07&#39;)  // SyntaxError</pre><p>To use it for money you have to work in minor units: 70.00 becomes 7000n cents, 1.5 ETH becomes 1500000000000000000n wei. That&#39;s a valid approach, and it brings some work with it:</p><pre>7n / 2n                     // 3n, division truncates, there&#39;s no rounding mode<br>1n + 1                      // TypeError: Cannot mix BigInt and other types<br>JSON.stringify({ a: 1n })   // TypeError: Do not know how to serialize a BigInt</pre><p>You track the scale of every currency yourself (2 decimals for USD, 8 for BTC, 18 for ETH), write your own rounding, convert percentages and rates into fixed-point integers, and handle serialization. The conversion into minor units also has to start from a string. BigInt(Math.round(0.07 * 100)) puts a float right back into the chain.</p><p>A minimal version looks like this:</p><pre>// &quot;70.00&quot; -&gt; 7000n, parsed from the string, never from a float<br>const toMinor = (s, decimals) =&gt; {<br>  const [int, frac = &#39;&#39;] = s.split(&#39;.&#39;)<br>  if (frac.length &gt; decimals) throw new Error(&#39;too many decimals&#39;)<br>  return BigInt(int + frac.padEnd(decimals, &#39;0&#39;))<br>}<br> <br>// division that rounds up<br>const ceilDiv = (n, d) =&gt; (n + d - 1n) / d<br> <br>const amount = toMinor(&#39;70.00&#39;, 2)          // 7000n<br>const fee = ceilDiv(amount * 10n, 10000n)   // 0.1% = 10 basis points -&gt; 7n, i.e. 0.07</pre><p>BigInt is a good fit for on-chain values, which are integers by definition. ethers v6 dropped its own BigNumber class in favor of native BigInt for wei amounts, which are whole numbers. Once you show those amounts to a person, convert currencies or apply a fee rate, you&#39;re back to decimals with rounding rules.</p><p>In practice most teams combine the two. Amounts are stored and sent as strings or integers in minor units, and calculations go through a decimal library with explicit rounding.</p><h3>Checklist</h3><ol><li>Money is never a number (or float, or double). Use a decimal type or integers in minor units.</li><li>Amounts travel as strings in JSON, in both directions.</li><li>Never call Number() or parseFloat() on an amount right before a request.</li><li>Always pass a rounding mode. bignumber.js defaults to ROUND_HALF_UP, which is wrong for both balances and fees.</li><li>Round spendable amounts down and fees up.</li><li>Take the precision of amounts and fees from the backend, per currency. Don’t hardcode toFixed(2).</li><li>For Max, ask the backend or mirror its fee model exactly, and validate amount + fee ≤ balance on the client too.</li></ol><p>The 10.4567 from the first example is a good test case. If your Max button shows 10.46 for it, you have the bug.</p><p>Originally published at <a href="https://umaniuk.dev/writing/money-math-in-javascript">umaniuk.dev</a>.</p><p>New posts go to my Telegram channel first: <a href="https://t.me/umaniuk_dev">t.me/umaniuk_dev</a></p><p>Questions, or a senior mobile role you think I’d fit? Message me on Telegram: <a href="https://t.me/umaniukbogdan">@umaniukbogdan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cfb03e34158" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>