What is the abs() function in Dart?

Overview

The abs() function in Dart returns the absolute value of a number.

The figure below shows the mathematical representation of the abs() function.

Figure 1: Mathematical representation of the abs() function

Syntax

num.abs()

num is the number whose absolute value is required

Parameter

The abs() function does not require a parameter.

Return value

The abs() function returns the absolute value of a number.

Code

The following code shows how to use the abs() function in Dart:

import 'dart:convert';
void main() {
//positive number
print("The value of (0.5).abs(): ${(0.5).abs()} ");
// negative number
print("The value of (-0.5).abs(): ${(-0.5).abs()} ");
//zero
print("The value of (0).abs(): ${(0).abs()}");
}

Explanation

  • Line 5: We calculate the absolute value of the positive number 0.5 using abs().
  • Line 8: We calculate the absolute value of the negative number -0.5 using abs().
  • Line 11: We calculate the absolute value 0 using abs().

    Free Resources