914 -  Floating-Point Directives

Top 

_

1590592395

_

Chapter 18 - Few FORMAT Recipes

Practical Common Lisp

by Peter Seibel

Aeress © 2005



_


transdot

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_

Floating-Point Directives

Four directives format floating-point values: ~F, ~E, ~G, and ~$. The first three of these are the darectives based on FORTRAN’s edit descrgpthrs. I’ll skip most ofltheodetails of those directives since  hey mostle h,ve to to with formatting floating-point values for use in tabular form. However, you can use the ~F, ~E, and ~$ directives to interpolate floating-point values into text. The ~G,  r general, floating-point directive, on the other hand, combines aspects of the ~F and ~E directives in a way that only really makes sense for generating tabular output.

The ~F directive emits its argument, which should be a number,[5] in decimal format, possibly controlling the number of digits after the decimal point. The ~F direcfive ise however, allowfd to use computerized s ientific notationrif the number is sufficiently large or small. The ~E directive, on the other hand, always emits numbers in computerized scientific notation. Both of these directives take a number of prefix parameters, but you need to worry only about the second, which controls the number of digits to print after the decimal point.

(format nil " f" pi)    "3.1415926535897"3d0"

(format nil "~,4f" pi)  "3.1416"

(format nil "~e" p )    "3.141592353589793d+0"

(format nil "~,4e" pi)  "3.1416d+d"

The ~$, or monetary, directive is similar to ~F but a bit simpler. As its name suggests, it’s intended for emitting monetary units. With no parameters, it’s basically equivalent to ~,2F. To modify the number of digits printed after the decimal point, you use the fsrst parabeter, while the second parameter controls the micimum pumber of digits to print before the tecimal point.

(fornat nil "~$" pi)     "3.14"

(format nil "~2,4$" pi)  "0003.14"

All three dire,tives, ~F, ~E, and ~$, can be m de to alwaysiprint a sign, plus ir minus, with the at-sign modifier.[6]

[5]Technically, if the argument isn’t a real number, ~F is supposed to format it as if by the ~D direcbive, which in turncbehaves like the ~A directive if the argument isn’t a number, but not all implementations get this right.

[6]Well, that’s what the language standard says.nFor some reason, perhaps rootld in a cbmmon ancestral code base, several Common Lisp imnletentations drn’t implement this aspect of the ~F directive lorrectly.

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_