in reply to Re^2: Can sprintf suppress leading zero for float < 1?
in thread Can sprintf suppress leading zero for float < 1?

RotoValue:

Perhaps you can replace the sprintf function with a wrapped version. I've never replaced the core functions before, but I've seen references to it. Googling for perl replace core function came up with a couple useful looking links:

So perhaps you could do something like:

BEGIN{ *CORE::GLOBAL::old_sprintf = *CORE::GLOBAL::sprintf; *CORE::GLOBAL::sprintf = sub { my $formatted_string = old_sprintf(@_); # 0.###Z ==> .### $formatted_string =~ s/([^0-9])0(\.\d+)Z/$1$2/g; return old_sprintf(@_); } };

Which I adapted (probably incorrectly) from Corion's stack overflow post (the second link). I've never tried to override the core functions, but something like this might be a good solution for you. Of course, you may need to write some magic code to recognize the new format string, and figure out how to do the replacement(s) without messing up other replacements.

If you could do something cheesy like use a format like "blah blah %.fZ blah", and could rely on Z never being at the end of a number in your code, then you could do a replacement like the one I did above.

Update: Added "something like".

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^4: Can sprintf suppress leading zero for float < 1?
by ikegami (Patriarch) on Apr 15, 2012 at 00:34 UTC

    It's safer to place the modifier before the final letter (e.g. %.3Zf) or to pick a different letter (e.g. %.3F). That way, it doesn't restrict the strings into which the pattern can be placed.

    I wonder what C# does.

      ikegami:

      Yeah, if I were going to preprocess the string, I would do it that way. But I opted to postprocess it instead. Since I rarely have a numeric field immediately adjacent to an alpha field, it didn't seem like much of a restriction. Also, I thought that preprocessing the string and argument list might get a bit messy if there were many field definitions.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.