用于格式化浮点数的字符串实用程序库?
String Utils Library for formatting Floats?
是否有用于格式化浮点数的 String Utils 库
FormatFloat('$0.00', FTotal)
FloatToStrF ?
我能够用
做我需要的
'$' + format('%0.2f', [FTotal]);
但只是好奇这些例程是否存在于某处?
底层 DWScript 编译器生成一个迷你 RTL,其中包含与上述 Format(fmt: String; args: array of const): String
类似的字符串函数。它还包含也可以在此上下文中工作的 function FloatToStr(f : Float; p : Integer = 99): String;
。
不幸的是,这些微型 RTL 函数的文档还有些不完善,但您可以在以下位置了解支持的内容:https://bitbucket.org/egrange/dwscript/wiki/InternalStringFunctions.wiki#!internal-string-functions
函数内部映射到
function Format(f,a) { a.unshift(f); return sprintf.apply(null,a) }
和
function FloatToStr(i,p) { return (p==99)?i.toString():i.toFixed(p) }
您也可以编写自己的代码来处理任何字符串格式。最好的办法是写一个浮动助手,这样你就可以写这样的东西:
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;
然而,这将为所有浮点值添加 toMyFormat 扩展。如果你想将它限制为一个新的类型,你可以这样写:
type
TMyFloat = Float;
TFloatHelper = strict helper for TMyFloat
function toMyFormat: String;
end;
[...]
希望对您有所帮助。
是否有用于格式化浮点数的 String Utils 库
FormatFloat('$0.00', FTotal)
FloatToStrF ?
我能够用
做我需要的 '$' + format('%0.2f', [FTotal]);
但只是好奇这些例程是否存在于某处?
底层 DWScript 编译器生成一个迷你 RTL,其中包含与上述 Format(fmt: String; args: array of const): String
类似的字符串函数。它还包含也可以在此上下文中工作的 function FloatToStr(f : Float; p : Integer = 99): String;
。
不幸的是,这些微型 RTL 函数的文档还有些不完善,但您可以在以下位置了解支持的内容:https://bitbucket.org/egrange/dwscript/wiki/InternalStringFunctions.wiki#!internal-string-functions
函数内部映射到
function Format(f,a) { a.unshift(f); return sprintf.apply(null,a) }
和
function FloatToStr(i,p) { return (p==99)?i.toString():i.toFixed(p) }
您也可以编写自己的代码来处理任何字符串格式。最好的办法是写一个浮动助手,这样你就可以写这样的东西:
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;
然而,这将为所有浮点值添加 toMyFormat 扩展。如果你想将它限制为一个新的类型,你可以这样写:
type
TMyFloat = Float;
TFloatHelper = strict helper for TMyFloat
function toMyFormat: String;
end;
[...]
希望对您有所帮助。