 [squeak-dev] Rounding to n significant digits?

Nicolas Cellier nicolas.cellier.aka.nice at gmail.com
Thu Aug 4 13:05:11 UTC 2011

One obvious user for this new method:

bench
"See how many times I can value in 5 seconds.  I'll answer a
meaningful description."
| startTime endTime count roundTo3Digits |
roundTo3Digits := [:num |
| rounded lowDigit |
rounded := (num * 1000) rounded. "round to 1/1000"
lowDigit := (rounded numberOfDigitsInBase: 10) - 3. "keep only first 3 digits"
rounded := rounded roundTo:(10 raisedTo: lowDigit).
(lowDigit >= 3 or: [rounded \\ 1000 = 0]) "display fractional part
only when needed"
ifTrue: [(rounded // 1000) asStringWithCommas]
ifFalse: [(rounded / 1000.0) printString]].
count := 0.
endTime := Time millisecondClockValue + 5000.
startTime := Time millisecondClockValue.
[ Time millisecondClockValue > endTime ] whileFalse: [ self value.
count := count + 1 ].
endTime := Time millisecondClockValue.
^count = 1
ifTrue: [ (roundTo3Digits value: (endTime - startTime) / 1000) , ' seconds.' ]
ifFalse:
[ (roundTo3Digits value: (count * 1000) / (endTime - startTime)) ,
' per second.' ]

Nicolas

2011/8/4 David T. Lewis <lewis at mail.msen.com>:
> On Thu, Aug 04, 2011 at 11:20:41AM +0200, Bert Freudenberg wrote:
>> Hi,
>>
>> I'd like to print decimal Floats with at most n significant digits. E.g.
>>
>>       123456 roundToSignificantDigits: 3
>>       => 123000
>>       0.00123456 roundToSignificantDigits: 3
>>       => 0.00123
>>
>> Would this generally be useful? If so, what would a good selector be? And what a good implementation? Instead of rounding I'd be happy to just get a String.
>
> IMO, if it isn't considered useful, then it *should* be ;) Having grown
> up with slide rules, I'm always annoyed by display of numbers with more
> precision than is physically possible or computationally meaningful.
> So +1 from me.
>
> Answering a String seems good, because the typical use case would
> be to display a number to some number of significant digits, but
> not to change the value of the number itself.
>
> Dave
>
>
>