Home > Net >  Dart: What is the difference between floor() and toInt()
Dart: What is the difference between floor() and toInt()

Time:11-03

I want to truncate all decimals of a double without rounding. I have two possibilities here:

double x = 13.5;
int x1 = x.toInt(); // x1 = 13
int x2 = x.floor(); // x2 = 13

Is there any difference between those two approaches?

CodePudding user response:

As explained by the documentation:

floor:

Rounds fractional values towards negative infinity.

toInt:

Equivalent to truncate.

truncate:

Rounds fractional values towards zero.

So floor rounds toward negative infinity, but toInt/truncate round toward zero. For positive values, this doesn't matter, but for negative fractional values, floor will return a number less than the original, whereas toInt/truncate will return a greater number.

  • Related