Effective Java, 2nd Edition Joshua Bloch said
The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.
For example, suppose you have $1.03 and you spend 42c. How much money do you have left?
System.out.println(1.03 - .42);
prints out 0.6100000000000001.
The right way to solve this problem is to use BigDecimal, int or long .
Never hold monetary values in a float variable. Floating point is not suitable for currency use either fixed-point or decimal values.
Better if provide the currency code and the same value in a few different formats. Consider this typical response for a amount of 0.00234
"amount": {
"currency": "USD",
"decimal": 0.00234,
"integer": 234000,
"integer_scale": 8,
"pretty": "\u0e3f 0.00234 BTC",
"string": "0.00234"
}
You have the option of using any of the provided number formats.
decimal: This is a decimal number
string: Same as decimal but quoted so your JSON library thinks it is a string.
pretty: A string ready to be shown to users. Includes appropriate currency sign and currency code.
currency: The 3-letter code for the currency.
Following are two examples API :
1 - Common Currency Codes in JSON
{
"USD": {
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
},
"CAD": {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
},
"EUR": {
"symbol": "€",
"name": "Euro",
"symbol_native": "€",
"decimal_digits": 2,
"rounding": 0,
"code": "EUR",
"name_plural": "euros"
}
}
https://gist.github.com/Fluidbyte/2973986
2 - Fixer API
http://api.fixer.io/latest
{
"base": "EUR",
"date": "2017-07-28",
"rates": {
"AUD": 1.4732,
"BGN": 1.9558,
"BRL": 3.7015,
"CAD": 1.4712,
"CHF": 1.1357,
"CNY": 7.9087,
"CZK": 26.048,
"DKK": 7.4364,
"GBP": 0.89568,
"HKD": 9.1613,
"HRK": 7.412,
"HUF": 304.93,
"IDR": 15639,
"ILS": 4.1765,
"INR": 75.256,
"JPY": 130.37,
"KRW": 1317.6,
"MXN": 20.809,
"MYR": 5.0229,
"NOK": 9.3195,
"NZD": 1.5694,
"PHP": 59.207,
"PLN": 4.2493,
"RON": 4.558,
"RUB": 69.832,
"SEK": 9.5355,
"SGD": 1.5947,
"THB": 39.146,
"TRY": 4.1462,
"USD": 1.1729,
"ZAR": 15.281
}
}
What is the standard for formatting currency values in JSON?