1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements rat-to-string conversion functions.
17 func ratTok(ch rune) bool {
18 return strings.IndexRune("+-/0123456789.eE", ch) >= 0
21 // Scan is a support routine for fmt.Scanner. It accepts the formats
22 // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
23 func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
24 tok, err := s.Token(true, ratTok)
28 if strings.IndexRune("efgEFGv", ch) < 0 {
29 return errors.New("Rat.Scan: invalid verb")
31 if _, ok := z.SetString(string(tok)); !ok {
32 return errors.New("Rat.Scan: invalid syntax")
37 // SetString sets z to the value of s and returns z and a boolean indicating
38 // success. s can be given as a fraction "a/b" or as a floating-point number
39 // optionally followed by an exponent. If the operation failed, the value of
40 // z is undefined but the returned value is nil.
41 func (z *Rat) SetString(s string) (*Rat, bool) {
47 // parse fraction a/b, if any
48 if sep := strings.Index(s, "/"); sep >= 0 {
49 if _, ok := z.a.SetString(s[:sep], 0); !ok {
54 if z.b.abs, _, _, err = z.b.abs.scan(strings.NewReader(s), 0, false); err != nil {
57 if len(z.b.abs) == 0 {
63 // parse floating-point number
64 r := strings.NewReader(s)
67 neg, err := scanSign(r)
74 z.a.abs, _, ecorr, err = z.a.abs.scan(r, 10, true)
81 exp, _, err = scanExponent(r, false)
86 // there should be no unread characters left
87 if _, err = r.ReadByte(); err != io.EOF {
96 // compute exponent power
101 powTen := nat(nil).expNN(natTen, nat(nil).setWord(Word(expabs)), nil)
108 z.a.abs = z.a.abs.mul(z.a.abs, powTen)
109 z.b.abs = z.b.abs[:0]
112 z.a.neg = neg && len(z.a.abs) > 0 // 0 has no sign
117 // scanExponent scans the longest possible prefix of r representing a decimal
118 // ('e', 'E') or binary ('p') exponent, if any. It returns the exponent, the
119 // exponent base (10 or 2), or a read or syntax error, if any.
121 // exponent = ( "E" | "e" | "p" ) [ sign ] digits .
122 // sign = "+" | "-" .
123 // digits = digit { digit } .
124 // digit = "0" ... "9" .
126 // A binary exponent is only permitted if binExpOk is set.
127 func scanExponent(r io.ByteScanner, binExpOk bool) (exp int64, base int, err error) {
131 if ch, err = r.ReadByte(); err != nil {
133 err = nil // no exponent; same as e0
146 fallthrough // binary exponent not permitted
149 return // no exponent; same as e0
153 if neg, err = scanSign(r); err != nil {
159 digits = append(digits, '-')
162 // no need to use nat.scan for exponent digits
163 // since we only care about int64 values - the
164 // from-scratch scan is easy enough and faster
166 if ch, err = r.ReadByte(); err != nil {
167 if err != io.EOF || i == 0 {
173 if ch < '0' || '9' < ch {
176 err = fmt.Errorf("invalid exponent (missing digits)")
181 digits = append(digits, byte(ch))
183 // i > 0 => we have at least one digit
185 exp, err = strconv.ParseInt(string(digits), 10, 64)
189 // String returns a string representation of x in the form "a/b" (even if b == 1).
190 func (x *Rat) String() string {
192 buf = x.a.Append(buf, 10)
193 buf = append(buf, '/')
194 if len(x.b.abs) != 0 {
195 buf = x.b.Append(buf, 10)
197 buf = append(buf, '1')
202 // RatString returns a string representation of x in the form "a/b" if b != 1,
203 // and in the form "a" if b == 1.
204 func (x *Rat) RatString() string {
211 // FloatString returns a string representation of x in decimal form with prec
212 // digits of precision after the decimal point. The last digit is rounded to
213 // nearest, with halves rounded away from zero.
214 func (x *Rat) FloatString(prec int) string {
218 buf = x.a.Append(buf, 10)
220 buf = append(buf, '.')
221 for i := prec; i > 0; i-- {
222 buf = append(buf, '0')
229 q, r := nat(nil).div(nat(nil), x.a.abs, x.b.abs)
233 p = nat(nil).expNN(natTen, nat(nil).setUint64(uint64(prec)), nil)
237 r, r2 := r.div(nat(nil), r, x.b.abs)
239 // see if we need to round up
241 if x.b.abs.cmp(r2) <= 0 {
244 q = nat(nil).add(q, natOne)
245 r = nat(nil).sub(r, p)
250 buf = append(buf, '-')
252 buf = append(buf, q.utoa(10)...) // itoa ignores sign if q == 0
255 buf = append(buf, '.')
257 for i := prec - len(rs); i > 0; i-- {
258 buf = append(buf, '0')
260 buf = append(buf, rs...)