class: Fraction
authorClaus Gittinger <cg@exept.de>
Thu, 06 Nov 2014 17:41:42 +0100
changeset 16938 ffe3202e45bd
parent 16937 faae893ed94b
child 16939 1c51cd6660e5
class: Fraction added: #readDecimalFractionFrom:onError: a utility: it is useful at more than one place (see iso8601 reader)
Fraction.st
--- a/Fraction.st	Thu Nov 06 17:23:25 2014 +0100
+++ b/Fraction.st	Thu Nov 06 17:41:42 2014 +0100
@@ -133,6 +133,40 @@
     "
 !
 
+readDecimalFractionFrom:aStringOrStream onError:exceptionBlock
+    "Read an arbitrary number (>0) of digits representing a decimal fraction."
+
+    |anyDigit factor fraction s ch|
+
+    s := aStringOrStream isStream ifTrue:[aStringOrStream] ifFalse:[aStringOrStream readStream].
+
+    factor := (1 / 10).
+    fraction := 0.
+    anyDigit := false.
+
+    [
+        ch := s peekOrNil.
+        ch notNil and:[ch isDigit].
+    ] whileTrue: [
+        s next.
+        anyDigit := true.
+        fraction := (ch digitValue) * factor + fraction.
+        factor := (factor / 10).
+    ].
+
+    anyDigit ifFalse: [^ exceptionBlock valueWithOptionalArgument: 'Missing digits in fraction'].
+    ^ fraction
+
+    "
+     Fraction readDecimalFractionFrom:'1'   onError:[nil]     -> 0.1
+     Fraction readDecimalFractionFrom:'123' onError:[nil]     -> 0.123  
+     Fraction readDecimalFractionFrom:'5'   onError:[nil]     -> 0.5  
+     Fraction readDecimalFractionFrom:'005' onError:[nil]     -> 0.005  
+     Fraction readDecimalFractionFrom:''    onError:[nil]     -> nil
+     Fraction readDecimalFractionFrom:'aa'  onError:[nil]     -> nil
+    "
+!
+
 readFrom:aStringOrStream onError:exceptionBlock
     |s numerator denominator|
 
@@ -1152,11 +1186,11 @@
 !Fraction class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic/Fraction.st,v 1.83 2014-07-09 16:21:06 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic/Fraction.st,v 1.84 2014-11-06 16:41:42 cg Exp $'
 !
 
 version_CVS
-    ^ '$Header: /cvs/stx/stx/libbasic/Fraction.st,v 1.83 2014-07-09 16:21:06 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic/Fraction.st,v 1.84 2014-11-06 16:41:42 cg Exp $'
 ! !