Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fractional part in dart

Tags:

flutter

dart

is there any way to print out the fractional part of a double,

My double number,

4734.602654867

I want only 6026 from it.

like image 531
Kermit Avatar asked Jul 01 '20 09:07

Kermit


People also ask

How do you find the fractional part?

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.

How do you get the decimal part of a number in darts?

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.

How do you find the fractional part of a float?

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.


Video Answer


3 Answers

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
like image 50
Jigar Patel Avatar answered Nov 22 '22 14:11

Jigar Patel


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..

like image 21
srikanth7785 Avatar answered Nov 22 '22 15:11

srikanth7785


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.

like image 36
Andrey Ozornin Avatar answered Nov 22 '22 15:11

Andrey Ozornin