Truncate a float and a double in java

一曲冷凌霜 提交于 2019-11-27 16:33:29

问题


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.


回答1:


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



回答2:


I have the same problem using Android, you can use instead:

DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);

but for this API Level 9 is required.

Another fast solution is:

double number = 12.43543542;
int aux = (int)(number*100);//1243
double result = aux/100d;//12.43



回答3:


double d = <some-value>;
System.out.println(String.format("%.2f", d - 0.005);



回答4:


Check java.math.BigDecimal.round(MathContext).




回答5:


take a look with DecimalFormat() :

DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);



回答6:


Try using DecimalFormat and set the RoundingMode to match what you need.



来源:https://stackoverflow.com/questions/10332546/truncate-a-float-and-a-double-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!