Пример #1
0
func (f *Float) StringBase(base int, ndigits uint) (string, error) {
	if f == nil {
		return "nil", nil
	}
	if base < 2 || base > 36 {
		return "", ErrInval()
	}
	var exp_ C.mp_exp_t
	p := C.mpf_get_str(nil, &exp_, C.int(base), C.size_t(ndigits), &f.i[0])
	exp := int(exp_)
	s := C.GoString(p)
	C.free(unsafe.Pointer(p))

	if len(s) == 0 {
		return "0", nil
	}
	var pre = ""
	if s[0:1] == "-" {
		pre = "-"
		s = s[1:]
	}

	var repeat = func(n int) string {
		if n < 0 {
			return ""
		}
		return strings.Repeat("0", n)
	}

	if exp < -8 || exp > 8 {
		s = s[0:1] + "." + s[1:] + "e" + strconv.Itoa(exp-1)
	} else if exp > 0 {
		s += repeat(exp - len(s) + 1)
		s = s[:exp] + "." + s[exp:]
	} else {
		s = "0." + repeat(-exp) + s
	}
	return pre + s, nil
}
Пример #2
0
func (f *Float) StringBase(base int, ndigits uint) (string, error) {
	if f == nil {
		return "nil", nil
	}
	if base < 2 || base > 36 {
		return "", os.ErrInvalid
	}
	f.doinit()
	var exp_ C.mp_exp_t
	p := C.mpf_get_str(nil, &exp_, C.int(base), C.size_t(ndigits), &f.i[0])
	exp := int(exp_)
	s := C.GoString(p)
	C.free(unsafe.Pointer(p))

	if len(s) == 0 {
		return "0", nil
	}

	if exp > 0 && exp < len(s) {
		return s[:exp] + "." + s[exp:], nil
	}
	return s + "e" + strconv.Itoa(exp), nil
}