## Extend the "Round" function's capability

Post your feature requets for new triggers, conditions, actions and other improvements.

Moderator: Martin

JC.INTERNET.STUFF
Posts: 26
Joined: 13 Jul 2017 08:47

### Extend the "Round" function's capability

Hi,

It would be great if the Round function could be extended to support the decimal place parameter . e.g. Round(4.501545, 3) = 4.502.

Or is there some other function with similar results, I can't seem to find.

Thanks.
Julian

Hit
Posts: 91
Joined: 20 Jan 2020 11:31

### Re: Extend the "Round" function's capability

I like this idea because it makes things easier.
Last edited by Hit on 29 Jul 2020 11:06, edited 1 time in total.

Hit
Posts: 91
Joined: 20 Jan 2020 11:31

### Re: Extend the "Round" function's capability

However, you made me think of two solutions. The first way is (best choice):

a = 4.501545;
p = 3; // p is precision of the number
// still use p to avoid redundancy variable
p = pow(10, p); // p = 1000
// Function pow(base, exponent) returns the value of the first argument raised to the power of the second argument.
a = round(a*p)/p; // = round(a*1000)/1000
// a = 4.502

You can also change p to any number. It will work.
You can use my code above.

Desmanto
Posts: 2709
Joined: 21 Jul 2017 17:50

### Re: Extend the "Round" function's capability

+1 for this. This make easier to round with base 10. Additionally, extend the same feature for ceil() and floor().

Meanwhile, we can use the old school method to round any number.

Round Integer
To round down integer to the nearest rounder, divide by rounder and multiply by rounder again.
Example : I usually round duration in ms to the nearest minute before show it. If the result is 9245678, using getDuration String() will show this as 2h 34m 5s 678ms, which is too long/detail for viewing. I want to truncate it at 2h 34m, at the minute level. 1 minute is 60 seconds or 60000 miliseconds, hence divider is 60000

Code: Select all

``````num = 9245678; // 2h 34m 5s 678ms
wor = getDurationString(num); //without round
i = num / 60000 * 60000; // round to minutes
j = getDurationString(i); // after round to minutes, 2h 34m``````

Round Decimal
To round decimal number, multiply by the rounder, round() it, then divide by the rounder again. (this is the same as Hit mention above)
Example : 4.501545, need to round at 3 decimal. We multiply it by 1000 first, become 4501.545, round it will round the decimal >> 4502.0 . Divide it again by 1000, we get 4.502.

Code: Select all

``````dnum = 4.501545;
f = round(dnum*1000)/1000``````
Index of Automagic useful thread List of my other useful posts (and others')
Xiaomi Redmi Note 5 (whyred), AOSP Extended v6.7 build 20200310 Official, Android Pie 9.0, Rooted.