Printing a float value into a string

I’m trying to output float values (actually, double float values) so that an exponent is only present if the value would otherwise not fit into the output buffer.

So for example 20.1 becomes 20.1 or 20.100000 (and not 2.0100E+01) but 1.0E20 becomes 1.000000E+20.

But if try to write the number to a String using Put from Float_IO, if I specify a positive Default_Exp I always get the exponent in the output. However, if I specify a Default_Exp of zero and the number is too large I get a Layout_Error.

I could catch the Layout_Error and then retry with a Default_Exp of 3 but this does not feel like a satisfying solution. I wonder what’s the best way to do it.

You need the Aft and Fore parameters.

The Put procedure which prints to a string only accepts Default_Aft.

I can choose Default_Aft and the buffer size so that the output fits into the buffer without an exponent but that’s not what I want. I want an exponent if the output would otherwise not fit into the buffer. I wonder if there is a way to this without having to calculate the length of the output or catching Layout_Error.

Perhaps you will find some inspiration in the HAC_Image function here:

1 Like

You can use an instantiation of PragmARC.Images.Float_Image.

For us, we use the ryu library (GitHub - ulfjack/ryu: Converts floating point numbers to decimal strings) with a thin Ada binding on top. It provides round-trip input/output, while being very fast.

1 Like

I often just write custom code for this kind of things… Some 'Image and 'Value attributes in Ada are not reversible. In the case of floating point types I also think Ada won’t like leading zeros in the 'Value.