6

I have a number that I want to take only the decimal part and convert it to an integer with certain precision.

How can I do that in Dart Language or flutter ?

For example :

turn this 247.64646122587197 into this 6464

Drop the float number and take only 4 decimals and convert it to an integer.

1
  • 2
    Not specific to dart, but floor((x % 1) * 10000) Commented Jan 14, 2020 at 16:57

4 Answers 4

8

Something like this should work:

((x % 1) * pow(10, 4)).floor()
Sign up to request clarification or add additional context in comments.

Comments

7
double value = 247.64646122587197;
double decimalValue = value - value.toInt();
print(decimalValue.toStringAsFixed(4))

Comments

5

you can also do that like this

void main() {
    final double abc=247.64646122587197;
    int y = int.tryParse(abc.toString().split('.')[1].substring(0,4));
    print(y);
}

output :6464

1 Comment

Technically works, but it's horribly inefficient. This would also throw an exception for numbers that have less than 4 decimal digits. As a rule of thumb, you shouldn't convert a number to a string unless it's absolutely necessary (and you better have a damn good reason for doing so if you are going to end up just converting it right back).
3

You could try this:

return (247.64646122587197 * 10000).toInt() % 10000;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.