How do I round a double to 5 decimal places, without using DecimalFormat
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Multiply by 100000. Add 0.5. Truncate to integer. Then divide by 100000.
Code:
If you are okay with external libraries, you can have a look at microfloat, specifically MicroDouble.toString(double d, int length).
I stumbled upon here looking for a way to limit my double number to two decimal places, so not truncating nor rounding it. Math.Truncate gives you the integral part of the double number and discards everything after the decimal point, so 10.123456 becomes 10 after truncation. Math.Round rounds the number to the nearest integral value so 10.65 becomes 11 while 10.45 becomes 10. So both of these functions did not meet my needs (I wish that .Net had overloaded both of these to allow truncating or rounding up to a certain number of decimal places). The easiest way to do what I needed is:
Try the following
Or if you want minimal amount of code
Use import static
And
regards,
Whatever you do, if you end up with a
double
value it's unlikely to be exactly 5 decimal places. That just isn't the way binary floating point arithmetic works. The best you'll do is "the double value closest to the original value rounded to 5 decimal places". If you were to print out the exact value of that double, it would still probably have more than 5 decimal places.If you really want exact decimal values, you should use
BigDecimal
.