我想将float值转换为String并创建以下简短示例:
with Ada.Text_IO;
procedure Example is
A : constant Float := -1.234;
B : constant Float := 123_456.789;
C : constant Float := 987.654_321;
package Float_IO is new Ada.Text_IO.Float_IO (Num => Float);
String_Float_A : String := " ";
String_Float_B : String := " ";
String_Float_C : String := " ";
begin
Ada.Text_IO.Put_Line (Float'Image (A));
Ada.Text_IO.Put_Line (Float'Image (B));
Ada.Text_IO.Put_Line (Float'Image (C));
Float_IO.Put
(To => String_Float_A,
Item => A,
Aft => 2,
Exp => 0);
Float_IO.Put
(To => String_Float_B,
Item => B,
Aft => 2,
Exp => 0);
Float_IO.Put
(To => String_Float_C,
Item => C,
Aft => 2,
Exp => 0);
Ada.Text_IO.Put_Line (String_Float_A);
Ada.Text_IO.Put_Line (String_Float_B);
Ada.Text_IO.Put_Line (String_Float_C);
end Example;
我的问题:我需要在调用足够长度的过程Put
之前创建字符串变量。如何在运行时动态完成?基本上我需要弄清楚点之前的位数。那么足够的字符串长度将是:1 (sign) + Number_Of_Dots + 1 (decimal separator) + Aft
。
可以计算十进制数点之前的位数,计算1加上数的整数部分的常用对数(基数10)的整数部分。
在阿达:
N := Integer (Float'Floor (Log (Float'Floor (abs X), 10.0))) + 1;
你的程序必须与Ada.Numerics.Elementary_Functions一起使用。如果数字为负数,则必须为减号添加空格。
如果整数部分为0,则此公式不起作用,但N显然为1。
你的例子使用Float
,也许作为一些更具体的real type的代理。如果您的实际数据更好地建模为decimal fixed point type,讨论here,不要忽视Edited Output for Decimal Types的便利性,讨论here。下面的例子使用字符串"+Z_ZZZ_ZZ9.99"
来构造所需输出picture的Image
。
安慰:
- 1.23
+ 123,456.79
+ 987.65
+1,000,000.00
码:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Editing; use Ada.Text_IO.Editing;
procedure Editing is
type Number is delta 0.000_001 digits 12;
type Numbers is array (Positive range <>) of Number;
package Number_Output is new Decimal_Output (Number);
Format_String : constant String := "+Z_ZZZ_ZZ9.99";
Format : constant Picture := To_Picture (Format_String);
Values : constant Numbers :=
(-1.234, 123_456.789, 987.654_321, Number'Last);
begin
for Value of Values loop
Put_Line (Number_Output.Image (Value, Format));
end loop;
结束编辑;
你可以创建一个函数来完成这项工作,如下所示:
with Ada.Text_IO;
with Ada.Strings.Fixed;
procedure Marcello_Float is
function Image (Item : Float;
Aft : Ada.Text_IO.Field := Float'Digits - 1;
Exp : Ada.Text_IO.Field := 3) return String
is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
Result : String (1 .. 128);
begin
Float_IO.Put (To => Result,
Item => Item,
Aft => Aft,
Exp => Exp);
return Ada.Strings.Fixed.Trim (Result,
Side => Ada.Strings.Both);
end Image;
A : constant Float := -1.234;
B : constant Float := 123_456.789;
C : constant Float := 987.654_321;
A_Image : constant String := Image (A, Aft => 2, Exp => 0);
B_Image : constant String := Image (B, Aft => 2, Exp => 0);
C_Image : constant String := Image (C, Aft => 2, Exp => 0);
use Ada.Text_IO;
begin
Put_Line (A'Image & " => " & A_Image);
Put_Line (B'Image & " => " & B_Image);
Put_Line (C'Image & " => " & C_Image);
end Marcello_Float;
我让Result
可笑得很长。我认识到计算一个确切的大小实际上会回答你原来的问题;只是懒惰。