'Avoiding scientific notation
I am experimenting using Go to interact with a Database and am running into issues when dealing with Decimal fields.
In this database most fields that are basically integer fields are typed as decimal with 0 precision... for example:
- Date fields are stored in YYYYMMDD format as decimal(8, 0)
- Id numbers are stored as decimal(9, 0)
Basically any int is stored as a decimal with 0 precision.
What I am attempting is to fill fields in a struct....
type Record struct {
ID uint
CHANGE_DATE uint
...
}
But when I get the fields from the database, they often come back in a format like this but only if the number is long enough: 2.0141208e+07
I have found that I can Scan into a float and then convert the float to an uint like this..
mydate := float32(0)
for rows.Next() {
r := Record{}
row.Scan(&.ID, &mydate)
myrecord.Change_date = uint(mydate)
}
If the ID is a large enough number then ParseInt fails and I find I have to do the float/int conversion as shown above.
Since I have many fields (almost all numbers) that I would need to do this with, I am wondering if there is a better way to go about this type conversion?
It may also be worth mentioning that this is a database from a packaged ERP system, so changing the table definitions is not an option and the reason I don't just make all fields float in Go is that I am trying to output json and I get the scientific notation in the json output.
Solution 1:[1]
I encountered the same issue when parsing JSON from a RPC server. I created a function to convert the scientific notation string back to uint like this:
func scientificNotationToUInt(scientificNotation string) (uint, error) {
flt, _, err := big.ParseFloat(scientificNotation, 10, 0, big.ToNearestEven)
if err != nil {
return 0, err
}
fltVal := fmt.Sprintf("%.0f", flt)
intVal, err := strconv.ParseInt(fltVal, 10, 64)
if err != nil {
return 0, err
}
return uint(intVal), nil
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |