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!

6
  • 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. Commented Jan 15, 2023 at 11:34
  • As well as BigDecimal("12.34"), there's String.toDouble() Commented Jan 15, 2023 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. Commented Jan 15, 2023 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? Commented Jan 15, 2023 at 12:58
  • Numbers can be converted to different bases using toString(radix: Int). But I agree with @gidds, more information would help. I think this is an X-Y problem. Commented Jan 15, 2023 at 13:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.