0

I working on a Hyperskill project in Kotlin to make a number converter which also converts fractions. Now I stuck with fraction converting.

else if (userInput.contains(".")) {
    var firstPart = userInput.substringBefore(".").toBigInteger()
    var secondPart = userInput.substringAfter(".").toString()

How can I convert the secondPart to its proper form? For example userInput is 15.375 and secondPart should be 0.375 Thanks in advance!

Tibor Tóth
  • 99
  • 12
  • To convert the second part of the input to its proper form, you can use the BigDecimal class. The BigDecimal class allows you to work with numbers with arbitrary precision, exapmle: val secondPartString = userInput.substringAfter(".").toString() , val secondPart = BigDecimal(secondPartString).multiply(BigDecimal.ONE), This will give you a BigDecimal representation of 0.375. – Mado Jan 15 '23 at 11:34
  • As well as [`BigDecimal("12.34")`](https://stackoverflow.com/q/28783918/4161471), there's [`String.toDouble()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-double.html) – aSemy Jan 15 '23 at 11:59
  • "As well as BigDecimal("12.34"), there's String.toDouble()" Not really understand your answer. I know I can convert the String to Double, but for converting a fractional number to other base I need to split it to two part, then convert them separately and at the end rejoin them. I think so. – Tibor Tóth Jan 15 '23 at 12:43
  • @TiborTóth It might help to know exactly what you plan to do with the two parts of the numbers; _how_ will be you converting them to another base? – gidds Jan 15 '23 at 12:58
  • Numbers can be converted to different bases using [`toString(radix: Int)`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-string.html). But I agree with @gidds, more information would help. I think this is an [X-Y problem](https://en.wikipedia.org/wiki/XY_problem). – aSemy Jan 15 '23 at 13:02
  • @aSemy To convert a fractional number from one base to another, you need to split the number into two parts: integer and fractional. Convert each part from their base to decimal independently and then convert them (once again, separately) to the target base. Finally, combine both parts and get the final result! This is the objective in the project. – Tibor Tóth Jan 15 '23 at 13:09

0 Answers0