Search code examples
dart

why abs() function in dart return negative number when not wrapped in parenthesis?


The abs() function has no effect When calling on negative number literal.

var y = -123.11.abs(); // prints -123.11

but other functions, for example floor() works fine

var y = -123.11.floor(); // prints -123

If I wrap the negative number literal in parenthesis it works fine

var y = (-123.11).abs(); // prints 123.11

Any help to understand this behaviour is appreciated.

The dart version I use is Dart VM version: 2.2.1-dev.0.0.flutter-571ea80e11 (Mon Mar 4 19:30:53 2019 +0000) on "windows_x64"

Update: Note: the floor() does not work correctly when applied on negative number as pointed by @HighPerformanceMark


Solution

  • According to Operator precedence and Dart Language Specification-123.11.abs() is the same as -((123.11).abs()).