Character based functions were discussed in the previous post. We’ll go ahead and look into the number function now. Some of my interesting observations are here –
- round(number, [decimal precision]) – This function rounds off a number to the lowest or highest value depending upon the decimal precision. The decimal precision is optional which means rounding to the nearest whole number. What happens when the decimal precision is negative. In such cases, the rounding off happens from the left of the decimal point. So, if it’s -1, then the rounding off happens at the first digit on the left side to the decimal point. It also happens to be significant digit.Lets look at something interesting –
round(number, decimal precision) Output round(32.54, 1) 32.5 round(32.55, 1) 32.6 round(32.55, 0) 33 round(32.45, 0) 32 round(32.45, -1) 30 round(32.45, -2) 0 round(52.45, -2) 100 Point to remember – If the decimal precision is negative, say -n, the significant digit will be the nth digit left to the decimal point. If the significant digit is less than 5, round the source number to the nearest multiple of 10^n less than source number. If the significant digit is 5 or more, round the source number to the nearest multiple of 10^n greater than source number.
So, in case of round(32.45, -1), n = 1 which means the significant digit is 2, which is less than 5 and therefore we’ll find the nearest multiple of 10 less than 32.45 which equals 30. Let’s take one more example – round(52.45, -2). Here n = 2 which makes 5 as the significant digit and therefore we’ll round it to the nearest multiple of 100 greater than 52.45, which equals 100.
- trunc(number, [decimal precision]) – It performs truncate operation on the numeric value on the decimal precision specified. in numeric truncation, the resulting value drops the numbers at the decimal precision and does not attempt to round-down or round-up if the decimal precision is positive.
If the decimal precision is negative (say -n), then the source number is zeroed down from the nth digit.
trunc(number, decimal precision) Output trunc(1666.54, -3) 1000 trunc(1666.66, -2) 1600 trunc(1601.916718) 1601 trunc(2601.958,1) 2601.9 trunc(2601.958,2) 2601.95