0

I just started coding in android studio and was creating calculator but now I'm stuck on one problem.

after struggling a lot I figured out how to make so u can use one dot but now I came across another problem which is after addition I cant seem to round up the decimals. when I do additions in decimals sometimes it gives me something like 1.9999999998 and I cant seem to round it up. for the reference I used Table Row in xml. if necessary I can show you what I have written so far. Thanks in advance.

3 Answers3

0

You need String.format(".1f", value). 1,99999 -> 1.99. If you need to round to higher value, please use ceil: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.math/ceil.html

Mike
  • 2,547
  • 3
  • 16
  • 30
0

For formatting numbers, you should always be using NumberFormat or similar.

NumberFormat lets you set a RoundingMode which will do what you want.

Or you could be like me and write your own formatter for numbers because the built-in one didn't do what I wanted.

Hakanai
  • 12,010
  • 10
  • 62
  • 132
0

If you care about exact decimal values, then don't use floating-point. Instead, use a type that's intended for storing exact decimal values, such as BigDecimal.

(Floating-point types such as Kotlin's Float and Double can hold numbers across a huge range of magnitude, and store and calculate with them efficiently. But they use binary floating-point, not decimal. So they're great when you care about doing calculations efficiently and flexibly — but not when you need to store exact decimal values. Most of the questions about floating-point on this site seem to be for the latter cases, unfortunately…)

Kotlin has lots of extensions making it almost as easy to handle BigDecimals as the native types. They're a little less efficient, but not by anywhere near enough to be significant in a calculator project. And they do exactly what you want here: storing and manipulating decimal numbers exactly.

And because they're exact, you shouldn't need to do any rounding — and probably won't need to do any formatting either.

(Just make sure you create them directly from strings, not from floats/doubles — which will already have been rounded to the nearest binary floating-point number.)

gidds
  • 16,558
  • 2
  • 19
  • 26