How to get the number of decimal places in a given number
I have a scenario where I need to get the number of decimal digits after the decimal point. Please refer below ex.
I want a function where I give this number as input and the function should return 4. As there are 4 decimal digits including trailing zeros.
var number = 123.1000;
Kindly someone help.
Karthik K R
Solved! Go to Solution.
var number_to_string = "123.1000";
var length = number_to_string.length;
var position = number_to_string.indexOf(".")+1;
You may need to convert duble to string.
Using Python you can do it in very simple way:
def decimals(x): return len(str(x - int(x))[2:])
Algorithm is the following:
0. Let say: x = 10.1234
1. (x - int(x)) or (x % 1) -> remain only floating signs: 0.1234
2. (str(x - int(x))[2:]) -> convert it into the string beginning after the floating point: "1234"
3. The length of the string is the number of decimals.
P.S. But in some cases you can have a rounding issues... So my solution is far from ideal...
Thanks for the solution.
Thanks baxatob for the code.
It looks like better to use aqConvert.FloatToStr() method and then parse the result using regular expression:
import re def decimals(yourFloat): converted_num = aqConvert.FloatToStr(yourFloat) pattern = re.compile("\.[0-9]*") res = re.search(pattern, converted_num) if res is not None: res = res.group(0) return len(res[1:])