2014-01-11 54 views
3

我正在寫一個應用程序,使用金錢並且想要非常準確的數字。我也使用mgo來存儲一些應用程序後的結果。我想知道是否有一種方法可以讓我在結構中使用math.Rat或godec,並將它存儲爲mgo中的數字?使用mgo精確計算小數點

這是代碼我希望運行的那種:

package main 

import(
    "fmt" 
    "math/big" 
    "labix.org/v2/mgo" 
) 

var mgoSession *mgo.Session 

type Test struct{ 
    Budget big.Rat 
} 

func MongoLog(table string, pointer interface{}) { 
    err := mgoSession.DB("db_log").C(table).Insert(pointer) 
    if err != nil { 
    panic(err) 
    } 
} 

func main(){ 
    var err error 
    mgoSession, err = mgo.Dial("localhost:27017") 
    defer mgoSession.Close() 
    if err != nil { 
    panic(err) 
    } 

    cmp := big.NewRat(1, 100000) 
    var test = Test{Budget : *big.NewRat(5, 10)} 
    MongoLog("test", &test) 
    for i := 0; i < 20; i++{ 
    fmt.Printf("Printf: %s\n", test.Budget.FloatString(10)) 
    fmt.Println("Println:", test.Budget, "\n") 
    test.Budget.Sub(&test.Budget, cmp) 
// test.Budget = test.Budget - cpm 
    } 
    MongoLog("test", &test) 
} 
+0

而你的代碼不會運行,因爲...? – nemo

+1

因爲mongo db不知道如何存儲big.Rat – Gary

+0

你可以只存儲大數字的「STRING」表示 – fabrizioM

回答

3

big.Rat基本上一對描述的有理數的分子和分母,分別未導出 int big.Int值。

您可以通過(*big.Rat).Denom(*big.Rat).Num輕鬆獲取兩個號碼。

然後將它們存儲在自己的結構,出口(大寫)字段:

type CurrencyValue struct { 
    Denom int64 
    Num int64 
} 

商店這與mgo並將其轉換回在你的應用程序中的*big.Rat通過big.NewRat

編輯:

尼克克雷格伍德在評論中正確指出,big.Rat實際上包括2 big.Int的值,而不是int的值,正如我寫的(容易忽略大寫字母i)。在BSON中很難表示big.Int,但int64應該覆蓋大多數使用情況。

+4

'big。 Rat'是一對無限精度的'big.Int',因此可能不適合'CurrencyValue'結構中的int。我不得不不同意@ Rick-777 - 「big.Rat」的無限精度不是32位。 –