I have seen several questions on this topic, but the answers do not seem useful to me.
I must create a function in PostgreSQL 10.5 that returns a number with N significant digits. I have tried different solutions for this problem, however I have a problem with a particular case. Below the example, where nmNumber
is the number of the input parameters and nmSf
is the number of significant digits.
SELECT round(nmNumber * power(10, nmSf-1-floor(log(abs(nmNumber ))))) / power(10, nmSf-1-floor(log(abs(nmNumber)))) result1,
round(nmNumber, cast(-floor(log(abs(nmNumber))) as integer)) result2,
floor(nmNumber / (10 ^ floor(log(nmNumber) - nmSf + 1))) * (10 ^ floor(log(nmNumber) - nmSf + 1)) result3;
If nmNumber
= 0.0801 and nmSf
= 2 then:
result 1 = 0.08; result2 = 0.08; result 3 = 0.08
The three results are incorrect given that:
- The zeros immediately after the decimal point are not significant digits.
- All non-zero digits are significant.
- The zeros after digits other than zero in a decimal are significant.
According to point 3, the correct result of the previous example is: 0.080 and not 0.08 and although mathematically it turns out to be the same, visually I must obtain this result. Some idea of ​​how I can solve my problem? I suppose that returning a VARCHAR
in exchange for a NUMERIC
is part of the solution to be proposed.
Some idea or I'm missing something. Thank you.