How can I truncate a double to only two decimal pl

2020-01-24 11:54发布

For example I have the variable 3.545555555, which I would want to truncate to just 3.54.

15条回答
Deceive 欺骗
2楼-- · 2020-01-24 12:57
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);

Check available RoundingMode and DecimalFormat.

查看更多
迷人小祖宗
3楼-- · 2020-01-24 12:57

Here is the method I use:

double a=3.545555555; // just assigning your decimal to a variable
a=a*100;              // this sets a to 354.555555
a=Math.floor(a);      // this sets a to 354
a=a/100;              // this sets a to 3.54 and thus removing all your 5's

This can also be done:

a=Math.floor(a*100) / 100;
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-01-24 12:57

This worked for me:

double input = 104.8695412  //For example

long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;

//result == 104.87

I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.

查看更多
登录 后发表回答