shuabing
shuabing

Reputation: 691

round a number to n decimal use format show different result

when I use format to get round value

".1f".format(0.55)

in some devices get result some samsung android 6.0

0.5

and other devices get result

0.6

if the value is 0.56 result is the same

0.6

It's that a bug, so I replace with that

val scale = 10.0.pow(2.0)
return ((round(0.55 * scale) / scale).toFloat())

Upvotes: 0

Views: 53

Answers (1)

diginoise
diginoise

Reputation: 7620

Are all the devices you test this on using the same locale?

You can use NumberFormat class with explicit rounding mode to ensure the same rounding rules:

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.setRoundingMode(RoundingMode.HALF_UP);    //rounding rules

nf.format(0.55d);

Upvotes: 1

Related Questions