Counterintuitive result in NumberFormat of Intl Package in Dart/Flutter

Viewed 1999

Why does NumberFormat(".##").format(17.46) leads to a string of 17.46 and not .46?

How can I achieve the latter, i.e. remove all digits in front of the decimal sign?

3 Answers

The NumberFormat only changes the way that a number is being displayed(basically, what formatting is). So you can't get the fractional part of the number(it doesn't work like pattern matching). Instead, you can use:

var num = 17.46;
var fraction = num.toString().split('.')[1];

Note: you can use '.' + num.toString().split('.')[1] to get the fraction part with the starting dot.

You can read more about the ICU Formatting that NumberFormat uses in this link.

ā€˜#’ in the NumberFormat class marks a single digit (omitted if the value is zero). So the number of hashtags after the decimal point denotes how many decimal places you want. For example:

double number = 12.1234;
NumberFormat(".#").format(number);     //prints 12.1
NumberFormat(".##").format(number);    //prints 12.12
NumberFormat(".###").format(number);   //prints 12.123
NumberFormat(".####").format(number);  //prints 12.1234

You could use substring and indexOf to remove everything before the decimal point, like so:

String str = "12.36";
String newStr = str.substring(str.indexOf('.') + 1);
//If you want to include the decimal point, remove the + 1.

Just as an alternative to the other answer, you can try to remove the integer part before converting to String, and not after:

String formatFraction (num a){
  num b = a.floor();
  num c = a-b;
  return NumberFormat(".##").format(c);
}

This way you can guarantee it will work despite of locale.

Related