开发者

How to display a floating point value as scientific parameter in Delphi

We have a frequent need to display floating point values in a scientific form with multiplier and units, for example the value of 1500 V (volts) would be displayed as 1.5 kV. A very small voltage of 1e-4 V would be displ开发者_运维知识库ayed as 100 uV. For years we've used an internally created routine to make this float to string conversion but I was minded to wonder recently whether such a means was more generally available?


I'm using this FormathWithPrefix function with little knowledge about logarithms... :)

Support SI prefixes range!

function FormathWithPrefix(n: double; decimals: integer): string;
var
  index: integer;
const
  Prefixes: array[-9..9]of string = ('<', 'y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '',
    'k','M', 'G', 'T', 'P', 'E', 'Z', 'Y', '>');   
begin
  index := round((Ln(n) / Ln(10) - 1) / 3);
  if index > 9 then 
    index := 9;
  if index < -9 then 
    index := -9;
  result := (FloatToStrF(n / Exp(index * 3 * ln(10)) , ffFixed, 20, decimals) + Prefixes[index]);
end;

begin
  n := 1500;
  Writeln(FormathWithPrefix(n, 1),'V');


If your goal is to make your routines more "native", you could take a look at the ConvUtils and StdConvs units and see if you could base your routines on the conversion functions offered by these units. (Not sure when those units were introduced. Quick google search suggest Delphi 6)

But that won't necessarily achieve much for you. (Depending on what you are looking to achieve)


Try here: http://www.delphibasics.co.uk/RTL.asp?Name=FloatToStrF

Particularly this one: `ShowMessage('Using 8,4 = '+FloatToStrF(amount1, ffFixed, 8, 4)); would indicate you can use something like this:

var 
  Answer:string;    
  thevolts:double;
begin
  Answer:= FloatToStrF(thevolts, ffFixed, 8, 4)+' kV'
end;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜