Home Segments Index Top Previous Next

496: Mainline

All that remains is to package what you have learned so far and to ensure that the resulting string is not too wide:

Float method definition • instance 
formatWithWidth: w andFraction: f 
  | string fraction | 
  fraction := (self - self truncated) abs. 
  string := self truncated printString , '.'. 
  f timesRepeat: [fraction := 10 * fraction. 
                  string := string , fraction truncated printString. 
                  fraction := fraction - fraction truncated]. 
  string size <= w 
    ifTrue: [^ ((String new: w - string size) atAllPut: $ ) , string] 
    ifFalse: [^ (String new: w) atAllPut: $*] 
Workspace
Transcript show: '|'  
                  , (547.08988 formatWithWidth: 8 andFraction: 2) 
                  , '|' 
                  , (-547.08988 formatWithWidth: 8 andFraction: 2) 
                  , '|' 
                  , (5470898.8 formatWithWidth: 8 andFraction: 2) 
                  , '|' 
Transcript 
|  547.08| -547.08|********|