简体   繁体   中英

java Long rounding to 2 decimals absolute value

long value = Math.round(Math.abs(object.getSomeStuff()/1000));

My object.getSomeStuff() returns a 3 digit integer value. I want to get the absolute value and also round to 2 digits.

Sample Input
123
-257

Sample Output
0.12
0.25

I don't exactly want to round it really, I want to truncate it, but that's a minor issue.

What am I doing wrong? I don't think the rounding is being done correctly here.

Sorry if I was not clear. The main issue is rounding which is not happening. I think i'm just seeing an integer value.

I assume you are getting 0 instead of 0.12 due to type issues (the entire operation happening as Integer ). If so try something like

long value = Math.abs((Float)(object.getSomeStuff()/10)/100);

Or

long value = Math.abs((object.getSomeStuff()/10)/100.0);

This should divide by 10 as Integer to eliminate one digit, and then divides by 100 as a Float to get the final value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM