Delphi - how do you format a real number with leading zeros?
Asked Answered
D

2

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

Doble answered 25/10, 2016 at 21:43 Comment(0)
L
13

Using SysUtils.FormatFloat:

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

will get 01.234

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

Larrikin answered 25/10, 2016 at 22:41 Comment(3)
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.Doble
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.Larrikin
This of course even works for int to string SNumber := FormatFloat('0##', Number)Misprint
F
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]) ;
Femoral answered 25/10, 2016 at 21:56 Comment(2)
Thanks for pointing out the error in the Format specifier - corrected.Doble
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.Femoral

© 2022 - 2024 — McMap. All rights reserved.