Page 1 of 1
Extend the "Round" function's capability
Posted: 28 Jul 2020 23:44
by JC.INTERNET.STUFF
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.
Please advise.
Thanks.
Julian
Re: Extend the "Round" function's capability
Posted: 29 Jul 2020 08:51
by Hit
I like this idea because it makes things easier.
Re: Extend the "Round" function's capability
Posted: 29 Jul 2020 08:53
by Hit
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.
Re: Extend the "Round" function's capability
Posted: 29 Jul 2020 11:24
by Desmanto
+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