Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format procedure similar to writeln

With writeln I can format numbers into a line of text.

var 
  file: text;
  mystring: string;

begin
  writeln(file,'Result is: ', var1:8:2,' | ', var2:8:2,' |');
end;

Is there a similar easy to use procedure in Delphi that would procedure similar result

  _format_string(mystring, 'Result is: ', var1:8:2,' | ', var2:8:2,' |');

Thank you.

like image 600
Michel Hua Avatar asked Aug 01 '13 12:08

Michel Hua


People also ask

What is the string format method?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

What string method is used to format values in a string?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do I format a string in C#?

The most common way how we format strings is by using string. Format() . In C#, the string Format method is used to insert the value of the variable or an object or expression into another string.


2 Answers

You use the Format function:

mystring := Format('The image dimensions are %d × %d.', [640, 480]);
like image 143
Andreas Rejbrand Avatar answered Sep 27 '22 20:09

Andreas Rejbrand


Technically the answer is "yes". But it's not recommended.

You can write your own text file device driver based on the System.TTextRec type.

I've done this in the past (especially in the Turbo Pascal era) for debugging purposes. It is a lot of work, and requires you to write a special MyAssign procedure, and be sure to close the Text file using the TTextRec in a try..finally block. Cumbersome, but doable.

A much easier alternative is using the Format function as described by Andreas Rejbrand.

The cool thing about using Format is that you use for Format Strings not only to parameterize things like width and precision inside that Format String, but also as paramaters like you normally would provide values.

You can get very close to using a width of 8 and a precision of 2, like the example in your question.

For instance, to quote the documentation:

Format ('%*.*f', [8, 2, 123.456]);

is equivalent to:

Format ('%8.2f', [123.456]);

That is a much overlooked feature of Format and Format Strings.

like image 42
Jeroen Wiert Pluimers Avatar answered Sep 27 '22 22:09

Jeroen Wiert Pluimers