Reputation: 61
Suppose, there is a floating number 2.78554 and I want to count the total decimal places present in number using Dart programming language.
Upvotes: 1
Views: 1992
Reputation: 71828
Your problem is slightly under-specified because you state it in terms of the double value, not the string representation.
There is no double with precisely the value 2.78554.
The closest double value is 2.78554000000000012704504115390591323375701904296875.
When you do toString
on a double, it choses the shortest representation of a rational number which is closer to that double value than to any other double value. This ensures that its short, and that if you run the string back through int.parse
, the double you get out will be the original, because it's the closest double value to the number represented by the string.
So, if you want the answer here to be 5, the number of digits in the string representation, going through toString
is probably the simplest thing to do.
int decimalCount(double value) {
var str = value.toString();
var dot = str.indexOf(".");
var e = str.indexOf("e", dot + 1);
if (e < 0) {
return str.length - (dot + 1);
}
// Has an exponent part, something like 1.234e-4. Try to compensate.
var decimals = e - (dot + 1);
var exponent = int.parse(str.substring(e + 1));
decimals -= exponent;
if (decimals < 0) return 0;
return decimals;
}
If you could ensure a representation without exponent forms, that would make things easier, but it's not possible when compiling to JavaScript. The .toStringAsFixed
is limited to 20 decimals.
It's definitely also possible to do the same computation that double.toString()
does, to find the precise value and the shortest representation, but it's quite complicated and intricate code, and easy to get wrong. I'd trust the platform instead.
Upvotes: 1
Reputation: 61
Here's the code
source.dart
main() {
double num = 2.78554;
int tenMultiple = 10;
int count = 0;
double manipluatedNum = num;
while (manipluatedNum.ceil() != manipluatedNum.floor()) {
manipluatedNum = num * tenMultiple;
count = count + 1;
tenMultiple = tenMultiple * 10;
}
print("$count decimal place(s) present in the $num (given number).");
}
Wanna follow me 😇 Instagram Twitter GitHub LinkedIn
Upvotes: 2
Reputation: 2911
You can consider your number as a String
, get only the characters after the point char and count the number of char in this substring.
void main() {
double n = 2.78554;
var decimals = n.toString().split('.')[1];
print(decimals.length);
}
Upvotes: 3