Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in Dart

Tags:

dart

I was looking up string classes and some other resources, trying to see how to format strings. Primarily, I am trying to Pad out a number to a string, but not precision.

example:

 int a = 0, b = 5, c = 15, d = 46;
 String aout = "", bout = "", cout="", dout="";

 //aout = "00"
 //bout = "05"
 //cout = "15"
 //dout = "46"

When i was looking at int to fixed string precision, it was mostly when dealing with decimals and not prepended padding.

My original thought is that I could do something related to sprintf, such as:

String out = sprintf("%02d", a);

but that didnt seem to work, mostly because It was saying that i am getting a nosuchmethod error. I was not sure if sprintf is in a different package other than core, as i thought this would be related directly to strings.

like image 927
Fallenreaper Avatar asked Dec 20 '16 20:12

Fallenreaper


People also ask

What is a string formatting?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. custom_string = "String formatting" print(f"{custom_string} is a powerful technique") Powered by Datacamp Workspace. String formatting is a powerful technique.

How do you write Dart strings?

String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings.

What is string interpolation in Dart?

String interpolation is the process of inserting variable values into placeholders in a string literal. To concatenate strings in Dart, we can utilize string interpolation. We use the ${} symbol to implement string interpolation in your code.


1 Answers

There's a String.padLeft method you can use:

String out = a.toString().padLeft(2, '0');
like image 180
Alexandre Ardhuin Avatar answered Oct 04 '22 22:10

Alexandre Ardhuin