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.ContainsRune("+-/0123456789.eE", ch)
22 var _ fmt.Scanner = &ratZero // *Rat must implement fmt.Scanner
24 // Scan is a support routine for fmt.Scanner. It accepts the formats
25 // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
26 func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
27 tok, err := s.Token(true, ratTok)
31 if !strings.ContainsRune("efgEFGv", ch) {
32 return errors.New("Rat.Scan: invalid verb")
34 if _, ok := z.SetString(string(tok)); !ok {
35 return errors.New("Rat.Scan: invalid syntax")
40 // SetString sets z to the value of s and returns z and a boolean indicating
41 // success. s can be given as a fraction "a/b" or as a decimal floating-point
42 // number optionally followed by an exponent. The entire string (not just a prefix)
43 // must be valid for success. If the operation failed, the value of z is
44 // undefined but the returned value is nil.
45 func (z *Rat) SetString(s string) (*Rat, bool) {
51 // parse fraction a/b, if any
52 if sep := strings.Index(s, "/"); sep >= 0 {
53 if _, ok := z.a.SetString(s[:sep], 0); !ok {
56 r := strings.NewReader(s[sep+1:])
58 if z.b.abs, _, _, err = z.b.abs.scan(r, 0, false); err != nil {
61 // entire string must have been consumed
62 if _, err = r.ReadByte(); err != io.EOF {
65 if len(z.b.abs) == 0 {
71 // parse floating-point number
72 r := strings.NewReader(s)
75 neg, err := scanSign(r)
81 // TODO(gri) allow other bases besides 10 for mantissa and exponent? (issue #29799)
83 z.a.abs, _, ecorr, err = z.a.abs.scan(r, 10, true)
90 exp, _, err = scanExponent(r, false)
95 // there should be no unread characters left
96 if _, err = r.ReadByte(); err != io.EOF {
100 // special-case 0 (see also issue #16176)
101 if len(z.a.abs) == 0 {
111 // compute exponent power
116 powTen := nat(nil).expNN(natTen, nat(nil).setWord(Word(expabs)), nil)
123 z.a.abs = z.a.abs.mul(z.a.abs, powTen)
124 z.b.abs = z.b.abs[:0]
127 z.a.neg = neg && len(z.a.abs) > 0 // 0 has no sign
132 // scanExponent scans the longest possible prefix of r representing a decimal
133 // ('e', 'E') or binary ('p', 'P') exponent, if any. It returns the exponent,
134 // the exponent base (10 or 2), or a read or syntax error, if any.
136 // exponent = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
137 // sign = "+" | "-" .
138 // digits = digit { digit } .
139 // digit = "0" ... "9" .
141 // A binary exponent is only permitted if binExpOk is set.
142 func scanExponent(r io.ByteScanner, binExpOk bool) (exp int64, base int, err error) {
146 if ch, err = r.ReadByte(); err != nil {
148 err = nil // no exponent; same as e0
161 fallthrough // binary exponent not permitted
164 return // no exponent; same as e0
168 if neg, err = scanSign(r); err != nil {
174 digits = append(digits, '-')
177 // no need to use nat.scan for exponent digits
178 // since we only care about int64 values - the
179 // from-scratch scan is easy enough and faster
181 if ch, err = r.ReadByte(); err != nil {
182 if err != io.EOF || i == 0 {
188 if ch < '0' || '9' < ch {
191 err = fmt.Errorf("invalid exponent (missing digits)")
196 digits = append(digits, ch)
198 // i > 0 => we have at least one digit
200 exp, err = strconv.ParseInt(string(digits), 10, 64)
204 // String returns a string representation of x in the form "a/b" (even if b == 1).
205 func (x *Rat) String() string {
206 return string(x.marshal())
209 // marshal implements String returning a slice of bytes
210 func (x *Rat) marshal() []byte {
212 buf = x.a.Append(buf, 10)
213 buf = append(buf, '/')
214 if len(x.b.abs) != 0 {
215 buf = x.b.Append(buf, 10)
217 buf = append(buf, '1')
222 // RatString returns a string representation of x in the form "a/b" if b != 1,
223 // and in the form "a" if b == 1.
224 func (x *Rat) RatString() string {
231 // FloatString returns a string representation of x in decimal form with prec
232 // digits of precision after the decimal point. The last digit is rounded to
233 // nearest, with halves rounded away from zero.
234 func (x *Rat) FloatString(prec int) string {
238 buf = x.a.Append(buf, 10)
240 buf = append(buf, '.')
241 for i := prec; i > 0; i-- {
242 buf = append(buf, '0')
249 q, r := nat(nil).div(nat(nil), x.a.abs, x.b.abs)
253 p = nat(nil).expNN(natTen, nat(nil).setUint64(uint64(prec)), nil)
257 r, r2 := r.div(nat(nil), r, x.b.abs)
259 // see if we need to round up
261 if x.b.abs.cmp(r2) <= 0 {
264 q = nat(nil).add(q, natOne)
265 r = nat(nil).sub(r, p)
270 buf = append(buf, '-')
272 buf = append(buf, q.utoa(10)...) // itoa ignores sign if q == 0
275 buf = append(buf, '.')
277 for i := prec - len(rs); i > 0; i-- {
278 buf = append(buf, '0')
280 buf = append(buf, rs...)