Menu

Why 0.1 + 0.2 breaks wallets: money math in JavaScript and every other language
πŸ“°

Why 0.1 + 0.2 breaks wallets: money math in JavaScript and every other language

DEV Community: reactnativeΒ·Bogdan UmaniukΒ·about 23 hours ago
#xn9sZ6bJ
#devtoreactnative#devto#dev#enter#exit
Reading 0:00
15s threshold

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.

The Max button that says "insufficient funds"

A user has 10.4567 USDT. The screen shows two decimals, so somebody writes:

const shown = balance . toFixed ( 2 ) // "10.46"

Enter fullscreen mode

Exit fullscreen mode

The user taps Max, the field fills with 10.46 , and the server answers "insufficient funds". They only have 10.4567 .

toFixed rounds to the nearest value, and .4567 is closer to .46 than to .45 . For anything a user can spend, that's the wrong direction. You need to round down:

import BigNumber from ' bignumber.js '

new BigNumber ( ' 10.4567 ' ). decimalPlaces ( 2 , BigNumber . ROUND_DOWN ).…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.