Reputation: 2023
i want to truncate a number after decimal through a built in function in java (not javascript). for example: 69.80000000001 to 69.8
please guide.
Upvotes: 1
Views: 4967
Reputation: 20604
You can use the scale functionality of BigDecimal:
new BigDecimal(69.80000000001).setScale(1, RoundingMode.HALF_UP).doubleValue();
This is for further using the rounded value. If you just want to print the rounded value but hold the original, DecimalFormat is the right choice as described by Matt.
Upvotes: 1
Reputation: 1976
What about the Decimal Format class?
I haven't tested this, but: Okay, this should work:
import java.text.DecimalFormat;
import java.math.RoundingMode;
public class Test
{
public static void main(String args[])
{
double i = 69.8999999999;
DecimalFormat format = new DecimalFormat("#.#");
format.setRoundingMode(RoundingMode.FLOOR);
String s = format.format(i);
i = Double.parseDouble(s);
System.out.println(i); //should be 69.8
}
}
Upvotes: 2