Java rounded to one decimal method:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
double data = 3.02;
//利用字符串格式化的方式实现四舍五入,保留1位小数
String result1 = String.format("%.1f",data);
//1代表小数点后面的位数, 不足补0。f代表数据是浮点类型。保留2位小数就是“%.2f”。
System.out.println(result1);//输出3.0
//利用BigDecimal来实现四舍五入.保留一位小数
double result2 = new BigDecimal(data).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
//1代表保留1位小数,保留两位小数就是2
//BigDecimal.ROUND_HALF_UP 代表使用四舍五入的方式
System.out.println(result2);//输出3.0
}
}
among them
; - ROUND_HALF_UP:: up situation encountered approximately .5, Example 2> 1.5
approximately .5 down situation is encountered, for example:: 1.5 ->; 1 ROUND_HALF_DOWN
A new new = the BigDecimal the BigDecimal (for 1.5);
System.out.println ( "Down =" + a.setScale (0, BigDecimal.ROUND_HALF_DOWN) + "/ TUP =" + a.setScale (0, BigDecimal.ROUND_HALF_UP));
Results : down = 1 up = 2
look at this example to understand!
Other Parameters
ROUND_CEILING
If the BigDecimal is positive, then do ROUND_UP operation; if it is negative, then do ROUND_DOWN operation.
ROUND_DOWN
never give up on (ie, truncate) the fractional increase in numbers before.
ROUND_FLOOR
If the BigDecimal is positive, as ROUND_UP; if it is negative, as ROUND_DOWN.
ROUND_HALF_DOWN
if the discarded fraction is> .5 for ROUND_UP; otherwise, for ROUND_DOWN.
ROUND_HALF_EVEN
if discarded digit to the left is an odd number, then for as ROUND_HALF_UP; if it is even, then for ROUND_HALF_DOWN.
As ROUND_HALF_UP
. If the discarded fraction> = 5, then for ROUND_UP; otherwise, for ROUND_DOWN.
ROUND_UNNECESSARY
The "pseudo-rounding mode" is actually specify the operations required to be accurate, hence no rounding.
ROUND_UP
always a non-zero discarded fraction (ie, truncate) before adding numbers.