3

is there a String Utils Library for formatting Floats

FormatFloat('$0.00', FTotal)

FloatToStrF ?

I was able to do what i needed with

  '$' + format('%0.2f', [FTotal]);

but just curious if those routines exist somewhere?

JakeSays
  • 2,048
  • 8
  • 29
  • 43

1 Answers1

3

The underlying DWScript compiler yields a mini RTL, which contains string functions like the mentioned Format(fmt: String; args: array of const): String. It also contains the function FloatToStr(f : Float; p : Integer = 99): String; which can work in this context as well.

Unfortunately, the documentation of these mini RTL functions is yet a little bit unpretty, but you can get an idea what's supported at: https://bitbucket.org/egrange/dwscript/wiki/InternalStringFunctions.wiki#!internal-string-functions

Internally the functions map to

function Format(f,a) { a.unshift(f); return sprintf.apply(null,a) }

and

function FloatToStr(i,p) { return (p==99)?i.toString():i.toFixed(p) }

You can also write your own code to handle any string formats. The best would be to write a float helper so that you could write something like:

type
  TFloatHelper = helper for Float
    function toMyFormat: String;
  end;

function TFloatHelper.toMyFormat: String;`
begin
  Result := '$' + format('%0.2f', [Self]);
end;

var value = 1.23;
var str = value.toMyFormat;

This however would add the toMyFormat extension for all float values. If you want to limit it to a new type you can write something like this:

type
  TMyFloat = Float;

  TFloatHelper = strict helper for TMyFloat
    function toMyFormat: String;
  end;

[...]

I hope this helps.

gabr
  • 26,580
  • 9
  • 75
  • 141
CWBudde
  • 1,783
  • 1
  • 24
  • 28
  • Thanks, that will def help me going forward. However, I was more interested in whether or not the Delphi like routines I am use to, existed in SMS, or If i had to use the Format routine and/or do what you have suggested. You have answered my question....i.e., the Delphi like routines I am use to DO NOT exist. - thanx – JakeSays Jan 06 '16 at 15:43