我是Golang的新手(但不是HANA),我正在尝试测试go-hdb以从 TCURR 表中提取数据(来自HANA DB SPS6)。根据我在该表中的理解, UKURS , FFACT 和 TFACT 都是HANA DB中的小数。 但是当从Go中检索时,我尝试使用row.Scan来获取Float64,如下所示:
var mandt, kurst, fcurr, tcurr, gdatu, datum string
var ukurs float64
var ffact, tfact float64
if err := rows.Scan(&mandt, &kurst, &fcurr, &tcurr, &gdatu, &ukurs, &ffact, &tfact, &datum); err != nil {
log.Fatal(err)
}
但是,唉,得到这样的错误
2016/08/18 10:18:31 sql: Scan error on column index 5: converting driver.Value type []uint8 ("@\xe2\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0060") to a float64: invalid syntax
我尝试阅读并理解它看起来需要uint8数据类型(或字节)的错误,但是,我仍然坚持如何将这些uint8 / byte转换为字符串。
之前是否有人遇到此问题以及如何获取十进制数据并正确显示(即将它们打印到控制台中)?
答案 0 :(得分:0)
在查看并理解驱动程序包一段时间后,我发现有一个功能实际上回答了我的问题。该函数位于decimal.go
内,函数名为decodeDecimal()
。由于它仅由内部使用,我复制源代码并粘贴到我的代码。
代码是这样的:
var mandt, kurst, fcurr, tcurr, gdatu, datum string
var ukurs, ffact, tfact []byte
if err := rows.Scan(&mandt, &kurst, &fcurr, &tcurr, &gdatu, &ukurs, &ffact, &tfact, &datum); err != nil {
WriteMsg("SCAN")
log.Fatal(err)
}
var bi big.Int
var z float64
var neg bool
var i int
var record []string
record = append(record, mandt)
record = append(record, kurst)
record = append(record, fcurr)
record = append(record, tcurr)
record = append(record, gdatu)
// ukurs
neg, i = decodeDecimal(ukurs, &bi)
z = BigIntToFloat(neg, &bi, i)
record = append(record, fmt.Sprintf("%.4f", z))
// ffact
neg, i = decodeDecimal(ffact, &bi)
z = BigIntToFloat(neg, &bi, i)
record = append(record, fmt.Sprintf("%.4f", z))
// tfact
neg, i = decodeDecimal(tfact, &bi)
z = BigIntToFloat(neg, &bi, i)
record = append(record, fmt.Sprintf("%.4f", z))
record = append(record, datum)
decodeDecimal()
func decodeDecimal(b []byte, m *big.Int) (bool, int) {
//bigint word size (*--> src/pkg/math/big/arith.go)
const (
dec128Bias = 6176
// Compute the size _S of a Word in bytes.
_m = ^big.Word(0)
_logS = _m>>8&1 + _m>>16&1 + _m>>32&1
_S = 1 << _logS
)
neg := (b[15] & 0x80) != 0
exp := int((((uint16(b[15])<<8)|uint16(b[14]))<<1)>>2) - dec128Bias
b14 := b[14] // save b[14]
b[14] &= 0x01 // keep the mantissa bit (rest: sign and exp)
//most significand byte
msb := 14
for msb > 0 {
if b[msb] != 0 {
break
}
msb--
}
//calc number of words
numWords := (msb / _S) + 1
w := make([]big.Word, numWords)
k := numWords - 1
d := big.Word(0)
for i := msb; i >= 0; i-- {
d |= big.Word(b[i])
if k*_S == i {
w[k] = d
k--
d = 0
}
d <<= 8
}
b[14] = b14 // restore b[14]
m.SetBits(w)
return neg, exp
}
功能BigIntToFloat()
func BigIntToFloat(sign bool, m *big.Int, exp int) float64 {
var neg int64
if sign {
neg = -1
} else {
neg = 1
}
return float64(neg*m.Int64()) * math.Pow10(exp)
}