var n = 20.238;
Math.round(n * 100) / 100
// => 20.24
Or more generally:
function roundWithPrecision(num, precision) {
var multiplier = Math.pow(10, precision);
return Math.round( num * multiplier ) / multiplier;
}
roundWithPrecision(20.238, 2)
// => 20.24
roundWithPrecision(20.238, 1)
// => 20.2
As others have pointed out, 20
and 20.00
are exactly the same, so if you want the user to see two digits after the decimal point even if they're zero, you'll have to use a string formatting function like toFixed
.
In the case of a JSON API, it's up to the consumer to decide how to store the value upon decoding it. Even if you were to output JSON that said { val: 20.00 }
a consumer will store it with whatever width it chooses. It might end up in a 32-bit float or a 64-bit float. It might end up in a string. It might end up in a MySQL database in a VARCHAR(6)
column. You can't control how the consumer treats your data, and this is by design.
There is no advantage to outputting { val: 20.00 }
over { val: 20 }
or { val: 20.00000 }
or { val: 2000e-2 }
. If you want the API consumer to assume two digits of precision, you should put that information in your API documentation. I would encourage this, as it will help other developers make decisions when implementing API clients.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…