For example I have the variable 3.545555555, which I would want to truncate to just 3.54.
相关问题
- 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
If you want that for display purposes, use
java.text.DecimalFormat
:If you need it for calculations, use
java.lang.Math
:Note first that a
double
is a binary fraction and does not really have decimal places.If you need decimal places, use a
BigDecimal
, which has asetScale()
method for truncation, or useDecimalFormat
to get aString
.If, for whatever reason, you don't want to use a
BigDecimal
you can cast yourdouble
to anint
to truncate it.If you want to truncate to the Ones place:
int
To the Tenths place:
int
double
Hundreths place
Example:
In this example,
decimalPlaces
would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)Bit Old Forum, None of the above answer worked for both positive and negative values ( I mean for the calculation and just to do truncate without Rounding). From the How to round a number to n decimal places in Java link
This method worked fine for me .
Results :
Maybe
Math.floor(value * 100) / 100
? Beware that the values like3.54
may be not exactly represented with adouble
.well this might be a little awkward, but i think it can solve your problem :)