How to do complex calculations in Bubble

The Bubble expression editor – you know… this one:

Bubble's expression editor

… is pretty good! But if you’re trying to do more complex mathematical expressions, you’ll find that the built-in editor has its limits. You can easily set up basic arithmetic like + – * and /, but at a certain point you’ll want to bring parentheses into the equation, and you may be surprised to find that you can’t.

The workaround for new Bubblers is often to temporarily store the numerical values in different Custom States, and calculate them over several actions in a workflow. It’ll work, but it’s not elegant. Yuck.

Enter the math.js plugin

The solution is the plugin Math.js. It uses the maths.js Javascript library that has a range of built-in functions and constants. Unlike custom states, the result of the expression is updated live – no workflows needed, just like the content of a group or the results of a search. Here’s an example from my advanced article on Recursive Workflows:

Note that the text in white is pure text – not a Bubble expression. In this way you can reference Bubble element’s and states directly in the expression, and then wrap it in parentheses and do arithmetic to your heart’s content. The great thing about the plugin is that it doesn’t rely on a third-party API.

Complex calculations and conversions

The library supports numbers, big numbers, complex numbers, fractions, units, strings, arrays, and matrices, so that you can do more complex calculations and even convert between units. Take a look at the screenshot below where I just casually add together centimeters and inches as if the two weren’t enemies to their death:

Screenshot showing unit conversion between cm and inches in Bubble.

A quick look at the Bubble debugger shows that we get the correct number, and can show the result as a text that includes the unit:

Doing calculations this way is a lot faster and lighter on your app than passing it through workflows, and the flexibility of the library is pretty awesome. Try it out!


More Posts

Understanding Bubble Groups

Bubble has five different group types. While they’re all used as containers, their use differs greatly. This article explains the difference between them in detail.

Bubble’s new expressions: SPLIT BY and ARBITRARY TEXT explained

Bubble quietly launched two new features in July 2021 that are quite useful: split by and arbitrary text. They’re both expressions that solve tiny problems that otherwise would require cumbersome workarounds, and are absolutely worth checking out. You’re not gonna

Combining icons and text in Bubble

Placing icons inside of your text elements by using BBCode is a quick way to reduce the total number of elements on your page and make sure your app runs smoothly. Read on for how to do it.

Leave A Reply

Your email address will not be published. Required fields are marked *