Commit f568ec46 authored by Luke Champine's avatar Luke Champine

marshal Currency as JSON string

Previously, the Currency type was marshalled as a JSON number.
This caused the value to be cast to a double when the JSON was
parsed by JavaScript.
parent 6cc0462d
......@@ -8,6 +8,7 @@ package types
// this value will not result in overflow.
import (
"bytes"
"errors"
"fmt"
"math"
......@@ -159,12 +160,16 @@ func (x Currency) Sub(y Currency) (c Currency) {
// MarshalJSON implements the json.Marshaler interface.
func (c Currency) MarshalJSON() ([]byte, error) {
return c.i.MarshalJSON()
// Must enclosed the value in quotes; otherwise JS will convert it to a
// double and lose precision.
return []byte(`"` + c.String() + `"`), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface. An error is
// returned if a negative number is provided.
func (c *Currency) UnmarshalJSON(b []byte) error {
// UnmarshalJSON does not expect quotes
b = bytes.Trim(b, `"`)
err := c.i.UnmarshalJSON(b)
if err != nil {
return err
......
......@@ -142,7 +142,7 @@ func TestCurrencyMarshalJSON(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(bMar30, cMar30) {
if !bytes.Equal(bMar30, bytes.Trim(cMar30, `"`)) {
t.Error("Currency does not match the marshalling of its math/big equivalent")
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment