Skip to main content

Command Palette

Search for a command to run...

Dart Number: Double Extension

Published
1 min readView as Markdown
Dart Number: Double Extension
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, extending the built-in double type directly isn't possible.

Here's why:

  • Primitive type: double is a primitive type in Dart. Unlike classes, primitive types cannot be subclassed or extended.

Here's what you can do achieve similar functionality:

  1. Extension methods:

    • While directly extending double isn't possible, you can achieve similar behavior using extension methods. Extensions allow adding methods to existing classes without modifying the original class.

Example:

Dart

    extension NumberRounding on num {
      // Rounds the number to a specified precision after the decimal point
      num toPrecision(int precision) {
        return num.parse((this).toStringAsFixed(precision));
      }
    }

    // Usage
    double value = 3.14159;
    double roundedValue = value.toPrecision(2); // 3.14
  1. Custom classes:

    • If you need more complex functionality beyond simple methods, create a custom class that wraps the double value and provides the desired behavior.

Example:

Dart

    class MyDouble {
      final double value;

      MyDouble(this.value);

      // Add custom methods here
      double getArea() {
        // Implement area calculation based on the value
        return value * value;
      }
    }

    // Usage
    MyDouble areaCalculator = MyDouble(5.0);
    double area = areaCalculator.getArea(); // 25.0

Remember, extensions are generally preferred for adding simple methods to existing types, while custom classes are more suitable for complex functionalities.

For more information, refer to the official Dart documentation on:

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.