Solidity – Why Doesn’t Solidity Perform Rounding to Nearest Whole Number?

contract-debuggingcontract-developmentfloating-pointsolidityuint256

The function getInt() is always returning more than 1. Shouldn't it do a round off for values less than 0.5 and return 0 ? Please check the imagetest function and let me know, if I am doing something incorrectly or if there is a way out.

Best Answer

When I try to run this code on remix it gave UnimplementedFeatureError: Not yet implemented - FixedPointType. Which you can see here This is not possible to use uint(3/30) as you are doing. Casting of any floating point using uint is not acceptable.

The Fixed Point are not yet unuseable in solidity as it documentation says:

Fixed point numbers are not fully supported by Solidity yet. They can be declared, but cannot be assigned to or from.

You may solve this problem by.

1)You may use divi function from ABDK Math 64.64 library. It divides one integer by another and returns the result as 64.64-bit fixed point number.

2)You can multiply the number by 10^n. Where 'n' is number of decimals in your return value.

((3/30)*3)*100

EDIT:

I want to understand - why does my test1 function doesn't return 0 but returns 1

Well the uint shouldn't return anything at all instead it must give an error as mentioned above.

Related Topic