skip to Main Content

Issue Description

I’m experiencing an issue with formatting Decimal values in Dart.

I have the following code snippet:

import 'package:decimal/Decimal.dart';

Decimal formatDecimal(Decimal value) {
  String formattedString = value.toStringAsFixed(2);
  return Decimal.parse(formattedString);
}

void main() {
  Decimal decimalValue = Decimal.parse('8');
  Decimal formattedValue = formatDecimal(decimalValue);
  
  print(formattedValue); // Output: 8
}

The expected output of the print statement is 8.00 in Decimal format, but the actual output is 8. It seems that the formatting is not being applied correctly.

Could someone please advise on how to correctly format the Decimal value 8 to 8.00 in Dart?

Thank you.

2

Answers


  1. Try now

    import 'package:decimal/decimal.dart';
    
    Decimal formatDecimal(Decimal value) {
      String formattedString = value.toStringAsFixed(2);
      
      // Append trailing zeros if necessary
      if (!formattedString.contains('.')) {
        formattedString += '.00';
      } else if (formattedString.endsWith('.')) {
        formattedString += '00';
      } else if (formattedString.endsWith('.0')) {
        formattedString += '0';
      }
      
      return Decimal.parse(formattedString);
    }
    
    void main() {
      Decimal decimalValue = Decimal.parse('8');
      Decimal formattedValue = formatDecimal(decimalValue);
      
      print(formattedValue); // Output: 8.00
    }
    
    Login or Signup to reply.
  2. According to the documentation, you can use the intl package to apply a formatter to your value:

    import 'package:decimal/decimal.dart';
    import 'package:decimal/intl.dart';
    
    main() {
      var value = Decimal.parse('1234.56');
      var formatter = NumberFormat.decimalPattern('en-US');
      print(formatter.format(DecimalIntl(value)));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search