How to convert a string to Double with decimal point in Kotlin - kotlin

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!

Related

Most idiomatic way to convert a Float value to a string without a decimal point in Kotlin

I'd like to convert a Float value to a String, but without a decimal point. For example, for the following code:
fun toDecimalString(value: Float): String {
// TODO
}
fun main() {
println("Result: ${toDecimalString(1.0f)}")
println("Result: ${toDecimalString(1.999999f)}")
println("Result: ${toDecimalString(20.5f)}")
}
I'd like the expected output to be:
1
1
20
As #Tenfour04 said, the answer is to first convert to an integer, by using .toInt(), which only leaves the digits left of the decimal point, and then convert to string using .toString().
.toInt().toString()
By converting to an Int before turning the input to a string, all decimal point values are dropped, e.g.:
fun toDecimalString(value: Float): String = "${value.toInt()}"

How to convert scientific notation number to regular decimal with places in kotlinlang

I was trying to loop over a map. But it converted my decimal number with scientific notation.
var myvar = mapOf("x" to 0.000001, "y" to 0.00000023)
for((k, v) in myvar){
println(v)
}
//Its showing the result
1.0E-6
2.3E-7
How can I convert this in regular decimal with places
Please help.

Convert String which is "float" to Integer

How to convert a string value which contains float representation to integer in kotlin?
I tried to convert string to float with .toFloat() and then converted it to an integer using toInt() and it works flawlessly.
But how to convert such string to integer directly?
val strDemo = "42.22"
val intDemo = strDemo.toInt()
snippet above throws NumberFormatException because it is not correct number representaion of Integer.
But, when I try
val strDemo = "42.22"
val intDemo = strDemo.toFloat().toInt()
it converts the data with no exception because string gets converted to float first. And there is a correct number representation for a Float value.
Now how to bypass the toFloat() method and convert strDemo to Integer directly?
There's no magic function that will convert a decimal/float string numbers to integer directly. It has to be done this way. Even if you found one, I'm sure that the process toFloat().toInt() still happen on that function.
So the solution that you can do is to create an extension of String like this:
StringExt.kt
fun String.floatToInt(): Int {
return this.toFloat().toInt()
}
You can use it like this:
val strDemo = "42.22"
val intDemo = strDemo.floatToInt()

Why single char and "single char String" not equal when converted to long (.toLong())

I wanted to sum the digits of Long variable and add it to the variable it self, I came with the next working code:
private fun Long.sumDigits(): Long {
var n = this
this.toString().forEach { n += it.toString().toLong() }
return n
}
Usage: assert(48.toLong() == 42.toLong().sumDigits())
I had to use it.toString() in order to get it work, so I came with the next test and I don't get it's results:
#Test
fun toLongEquality() {
println("'4' as Long = " + '4'.toLong())
println("\"4\" as Long = " + "4".toLong())
println("\"42\" as Long = " + "42".toLong())
assert('4'.toString().toLong() == 4.toLong())
}
Output:
'4' as Long = 52
"4" as Long = 4
"42" as Long = 42
Is it a good practice to use char.toString().toLong() or there is a better way to convert char to Long?
Does "4" represented by chars? Why it is not equal to it char representation?
From the documentation:
class Char : Comparable (source) Represents a 16-bit Unicode
character. On the JVM, non-nullable values of this type are
represented as values of the primitive type char.
fun toLong(): Long
Returns the value of this character as a Long.
When you use '4' as Long you actually get the Unicode (ASCII) code of the char '4'
As mTak says, Char represents a Unicode value. If you are using Kotlin on the JVM, you can define your function as follows:
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()
There's no reason to return Long rather than Int, but I've kept it the same as in your question.
Non-JVM versions of Kotlin don't have the Character class; use map {it - '0'} instead.

java.text.DecimalFormat equivalent in Objective C

In java, I have
String snumber = null;
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number); //'number' is of type 'long' passed to a function
//which has this code in it
I am not aware of the DecimalFormat operations in java and so finding it hard to write an equivalent Obj C code.
How can I achieve this? Any help would be appreciated.
For that particular case you can use some C-style magic inside Objective-C:
long number = 123;
int desiredLength = 10;
NSString *format = [NSString stringWithFormat:#"%%0%dd", desiredLength];
NSString *snumber = [NSString stringWithFormat:format, number];
Result is 0000000123.
Format here will be %010d.
10d means that you'll have 10 spots for number aligned to right.0 at the beginning causes that all "empty" spots will be filled with 0.
If number is shorter than desiredLength, it is formatted just as it is (without leading zeros).
Of course, above code is valid only when you want to have numbers with specified length with gaps filled by zeros.
For other scenarios you could e.g. write own custom class which would use appropriate printf/NSLog formats to produce strings formatted as you wish.
In Objective-C, instead of using DecimalFormat "masks", you have to live with string formats.