is there any way to print out the fractional part of a double,
My double number,
4734.602654867
I want only 6026
from it.
For example, if the problem is “What is 5/7 of 93,” then “5” is the numerator, “7” is the denominator and “93” is the whole number. Divide the whole number by the denominator. Using the same example, divide 93 / 7 = 13.3. Multiply the quotient from the previous step by the numerator.
Dart round double to N decimal places – Multiply the number by 10^N (using pow() function), then round the result to integer and divide it by 10^N . For example, we want to round double to 2 decimal places.
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
There is a truncate()
function for double type which returns the integer part discarding the fractional part. We can subtract that from the original double to get the fraction.
double myDouble = 4734.602654867;
double fraction = myDouble - myDouble.truncate();
print(fraction); // --> prints 0.602654867
Edit: If we want 4 digits specifically from the fractional part, we can do this..
int result = (fraction*10000).truncate();
print(result); // --> prints 6026
To do all this one line, we can do it like this..
int result = ((myDouble - myDouble.truncate())*10000).truncate(); // <-- 6026
You can do that using split()
Like this..
var s = 4734.602654867;
var a = s.toString().split('.')[1]. substring(0,4); // here a = 6026
Hope it solves your issue..
Something like
import 'dart:math' show pow;
var number = 4734.602654867;
var wantedDigits = 4;
var fraction = (number % 1 * pow(10, wantedDigits)).floor();
print(fraction);
should work.
Dartpad example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With