Lisp HUG Maillist Archive

Format ~g directive question

Hi,

This is probably a beginners kind of question, but it really puzzles me.

I want to print floating point numbers that conform to the JSON  
specification,
http://www.json.org or http://www.ietf.org/rfc/rfc4627.txt

Examples are: 1.5 -1.5 1.5E10 1.5E-40

So I don't want CL's D notation to be used anywhere, and I don't want
exponential notation unless it is really needed. It is easy to handle  
pure integers seperately.

So I thought ~g would do the trick, and it does, but it does something  
else as well:

CL-USER 3 > (format nil "~,,,,,,'Eg" pi)
"3.141592653589793    "

CL-USER 4 > (format nil "~,,,,,,'Eg" (expt 2 30))
"1.0737418E+9"

It prints excess spaces at the end, even without any options:

CL-USER 5 > (format nil "~g" pi)
"3.141592653589793    "

Not just in LispWorks, but in other CL's as well, so this is probably  
somehow normal behavior.

So the question is, what is going on, and how can I solve this
without doing something as silly as trimming the excess spaces ?

Thx,

Sven




Re: Format ~g directive question

Sven,

we had a similar issue with other Lisps, and our workaround was to
bind *read-default-float-format* to 'double-float and then use ~F to
print floats.  Give it a try and let me know if that works for you,
too.

-Hans

On Tue, Apr 29, 2008 at 1:36 PM, Sven Van Caekenberghe <sven@beta9.be> wrote:
> Hi,
>
>  This is probably a beginners kind of question, but it really puzzles me.
>
>  I want to print floating point numbers that conform to the JSON
> specification,
>  http://www.json.org or http://www.ietf.org/rfc/rfc4627.txt
>
>  Examples are: 1.5 -1.5 1.5E10 1.5E-40
>
>  So I don't want CL's D notation to be used anywhere, and I don't want
>  exponential notation unless it is really needed. It is easy to handle pure
> integers seperately.
>
>  So I thought ~g would do the trick, and it does, but it does something else
> as well:
>
>  CL-USER 3 > (format nil "~,,,,,,'Eg" pi)
>  "3.141592653589793    "
>
>  CL-USER 4 > (format nil "~,,,,,,'Eg" (expt 2 30))
>  "1.0737418E+9"
>
>  It prints excess spaces at the end, even without any options:
>
>  CL-USER 5 > (format nil "~g" pi)
>  "3.141592653589793    "
>
>  Not just in LispWorks, but in other CL's as well, so this is probably
> somehow normal behavior.
>
>  So the question is, what is going on, and how can I solve this
>  without doing something as silly as trimming the excess spaces ?
>
>  Thx,
>
>  Sven
>
>
>
>


Re: Format ~g directive question

(let ((*read-default-float-format* 'double-float))
        (format t "~,,F" (expt pi 100)))

yields

5.187848314319588E49

in Lispworks and

5.187848314319599E+49

in CCL.  Maybe I'm missing something?

-Hans


Re: Format ~g directive question

I must pass the ball to someone with more internals knowledge.  I have
used this trick with CCL where it worked, but it seem to be a
nonportable hack more than anything else.

-Hans


Updated at: 2020-12-10 08:43 UTC