is there any way to print out the fractional part of a double,
My double number,
4734.602654867
I want only 6026 from it.
is there any way to print out the fractional part of a double,
My double number,
4734.602654867
I want only 6026 from it.
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
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.
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..
final double number = 4734.602654867;
final String result = number.toStringAsFixed(5).split('.').last.substring(0,4);
void main() {
double d = 4734.602654867;
print(((d - d.floor()) * 10000).floor()); // --> prints 6026
}
floor method returns the decimal part of the number
I got a simpler and straight forward answer, especially if you want to still use the fractional part as decimal, and not as a string
` double kunle=300.0/7.0; // the decimal number
int s=kunle.floor(); // takes out the integer part
double fractionalPart=kunle-s; // takes out out the fractional part
print(fractionalPart); // print the fractional part }`