The input data for the program is JSON with BigDecimal value like this example: 345.0197 I have 2 problems:
- Some fields has to display different number of digits after comma:
- 3 digits after comma like: 345.019
- 2 digits, like: 345.01
- 1 digit, like: 345.0
- The integer before comma must have bigger text size than decimals after comma. Like on this image:
I need the function in Java or Kotlin which can return the decimal cut according to number of digits desired after comma (3, 2 or 1) and this decimal separated from integer, that I can apply different layout style at final result.
What’s the best way to do it?
Advertisement
Answer
Maybe something like this?
var decimal_places = 3 val value = 745.49.toBigDecimal() val part_a = value.toBigInteger() val part_b = value.subtract(BigDecimal(part_a)).toString().drop(2).take(decimal_places)
Or a more mathematical way:
val part_a = value.toBigInteger() val part_b = (value.subtract(BigDecimal(part_a)).toDouble() * Math.pow(10.toDouble(), decimal_places.toDouble())).toInt()