8

I need to format a real number with leading zeros in the whole number part prior to the decimal point. I know how to achieve this with integers, but the syntax for reals escapes me.

Number  := 1.234 ;
SNumber := Format ('%2.3f', [Number]) ;

This gives SNumber = ' 1.234' but I want '01.234'. Number is always 0..99.999

Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
rossmcm
  • 5,493
  • 10
  • 55
  • 118

2 Answers2

13

Using SysUtils.FormatFloat:

SNumber := FormatFloat('0#.###',Number); 

will get 01.234

Six placeholders and a leading zero means to add leading zeros.

LU RD
  • 34,438
  • 5
  • 88
  • 296
  • Thanks - yours was a "leaner" solution. I forgot to ask about the *trailing* zeros also (i.e. I want 1.23 to display as `01.230`. On the basis of the syntax to include leading zeros I assume that `FormatFloat ('0#.##0', Number) ;` is what I want - it seems to work. – rossmcm Oct 25 '16 at 23:09
  • Indeed, doc says: *The locations of the leftmost '0' before the decimal point in the format string and the rightmost '0' after the decimal point in the format string determine the range of digits that are always present in the output string.* – LU RD Oct 26 '16 at 08:57
  • 1
    This of course even works for int to string `SNumber := FormatFloat('0##', Number)` – Andreas Walter Dec 21 '17 at 11:46
6

The width of the string you want is 6 not 2. Additionally you want to replace the padded spaces with '0'.

SNumber := StringReplace(Format('%6.3f', [Number]), ' ', '0', [rfReplaceAll]) ;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • Thanks for pointing out the error in the `Format` specifier - corrected. – rossmcm Oct 25 '16 at 23:04
  • You're welcome. That *error* is the important part of my answer. Width specifier applied only to the whole part of the number is a common misconception. I didn't post an answer just to tell characters in a string can be replaced. As such, I roll-backed your question. – Sertac Akyuz Oct 26 '16 at 00:42