truncating number after decimal...through built in function in java
i want to truncate a number after decimal through a built in function in java (not javascript). for example开发者_StackOverflow: 69.80000000001 to 69.8
please guide.
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
}
}
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.
精彩评论