Skip to content

Instantly share code, notes, and snippets.

@erluxman
Created June 16, 2020 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erluxman/3bdfd6923d1e8788ed81eaae9e77655f to your computer and use it in GitHub Desktop.
Save erluxman/3bdfd6923d1e8788ed81eaae9e77655f to your computer and use it in GitHub Desktop.
void main() {
print(30.88922.withDecimalPoints(3)); //30.889
print(30.88922.withDecimalPointsFormatted(1)); //30.9
print(30.withDecimalPoints(3)); //30.0
print(30.withDecimalPointsFormatted(3)); //30.000
}
extension DecimalPoints on num {
double withDecimalPoints(int n) {
return num.parse(this.toStringAsFixed(n));
}
// Adds necessary non significant 0s at end for formatting
String withDecimalPointsFormatted(int n) {
var numString = this.withDecimalPoints(n).toString();
var missingZeros = n - numString.split(".")[1].length;
return numString + "0" * missingZeros;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment