在java中截断一个float和一个double [英] Truncate a float and a double in java

查看:321
本文介绍了在java中截断一个float和一个double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我的要求:
1.如果我有12.49688f,应该打印为12.49而不舍弃
2.如果是双倍的12.456,则应打印为12.45,而不舍入
3.无论如何,如果值为12.0,则应打印为只有12元。



条件3要始终牢记在心。它应该与截断逻辑并发。

解决方案

尝试这个 -

  DecimalFormat df = new DecimalFormat(### #); 
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));

这里,我们使用十进制格式化来形成。圆形模式设置为DOWN,因此它不会自动舍入小数位。



预期结果是:

  12.49 
12.45
12


I want to truncate a float and a double value in java.

Following are my requirements: 1. if i have 12.49688f, it should be printed as 12.49 without rounding off 2. if it is 12.456 in double, it should be printed as 12.45 without rounding off 3. In any case if the value is like 12.0, it should be printed as 12 only.

condition 3 is to be always kept in mind.It should be concurrent with truncating logic.

解决方案

try this out-

DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));

Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.

The expected result is:

12.49
12.45
12

这篇关于在java中截断一个float和一个double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆