1

How to convert 100.00 or 100.0 to 100 and if the number is 100.23 it should keep it as the same 100.23.

In dart, I tested these functions floor() and round() they return 100 even if the number is 100.23.

How to solve it?

Thanks

Akif
  • 7,098
  • 7
  • 27
  • 53
blue492
  • 540
  • 1
  • 6
  • 21

3 Answers3

4

By using the intl package of flutter to format the number. please refer below

import 'package:intl/intl.dart' as intl;

  @override
  void initState() {
    var valueFormat = intl.NumberFormat.decimalPattern();
    print(valueFormat.format(100.234));
    print(valueFormat.format(100.00));
  }

OutPut

I/flutter ( 5364): 100.234
I/flutter ( 5364): 100
2
double input1 = 100.00;  //100
double input2 = 100.0; //100
double input3 = 100.23; //100.23

RegExp regex = RegExp(r"([.]*0)(?!.*\d)");

String str = input1.toString().replaceAll(RegExp(r"([.]*0)(?!.*\d)"), "");
Ashok
  • 3,190
  • 15
  • 31
  • stolen from here https://stackoverflow.com/questions/55152175/how-to-remove-trailing-zeros-using-dart – Nagual Feb 04 '21 at 10:01
  • I didn't even check that and how can you say I've stolen from that and I didn't even check your comment. – Ashok Feb 04 '21 at 10:34
1

Until you get a better answer, you can do something like the following steps:

double value = 100.32739273;
String formattedValue = value.toStringAsFixed(2);

print(formattedValue);

if (formattedValue.endsWith(".00")) {
  formattedValue = formattedValue.replaceAll(".00", "");
}

print(formattedValue);
Akif
  • 7,098
  • 7
  • 27
  • 53
  • Thanks, I wanted to implement something like this but I am searching if there is a built function in dart which can do the same. – blue492 Feb 04 '21 at 08:36