# How can I implement rational operations in Solidity? [duplicate]

First, I know that fixed point integers are coming...but I really need to know how to accomplish a simple operation who return a rational number.

For example, get 2% of 350 is easy implementing: 350/50 because the result is an integer = 7. However, 2% of 340 is not easy...the result is 6,8...so how can I get 0.8?

I´ve tried several ways...but I can't do it. Is there any library or smt related to math applied to division?

You can easily handle that issue by working in hundreds or thousands or whatever precision you need.

Working in thousands, for example, means that you would not calculate 2% of 340, but 2% of 340000. The result will be 6800, which is an integer. Now that you know that your smart contract works in thousands, the part that makes the function call (web3?), and that probably is able to handle floats, just has to divide the result of 6800 by 1000.

This is basically the same as using fixed point math, the only difference is that in fix point math, you are working with precisions of powers of two, which might feel unusual, since we usually think in fractions of powers if ten.

Note that if you do multiplication/division of numbers that are "in thousands" you need to divide/multiply after the operation by 1000, in order to return to a precision of thousands.

You can easily get the percentage by multiplying then dividing your value.

Examples:

``````10% of 100 you can do 100 × 10 ÷ 100 = 10

6% of 100 you can do 100 × 6 ÷ 100 = 6

6.5% of 50 you can do 50 × 65 ÷ 1000 = 3.25
``````
• I´ve already tried that way and doesn´t work. Dec 13, 2017 at 19:03
• @jorge How does it not work?
– I.B
Dec 13, 2017 at 19:10
• because in the third case...solidity never is gonna give u back a fixed point number 3.25...just 3. Dec 13, 2017 at 19:25
• @jorge You usually work with a 18 decimal token so it's very rare that you actually use the equivalent of 50 Wei in your operations
– I.B
Dec 13, 2017 at 19:27
• But not everybody is working with tokens in his contract...Although for this time, the unique solution is work with 18 decimals in everything... Dec 20, 2017 at 1:22