How to convert toFixed(2) in Kotlin - kotlin

What should I write in the place of area.toFixed(2)
fun main(args: Array<String>) {
val a = 20
val h = 30
val area = a * h / 2
println("Triangle area = ${area.toFixed(2)}")
}

I think you really meet a problem that how to convert Javascript code to Kotlin code. You need to ask the question clearly at next time, :). you can use String#format instead, for example:
println("%.2f".format(1.0)) // print "1.00"
println("%.2f".format(1.253)) // print "1.25"
println("%.2f".format(1.255)) // print "1.26"
AND the area is an Int which means it will truncates the precision, Kotlin doesn't like as Javascript use the numeric by default, so you should let a*h divide by a Double, then your code is like as below:
// v--- use a `Double` instead
val area = a * h / 2.0
println("Triangle area = ${"%.2f".format(area)}")

Related

How do I reduce the digits of an incoming multi-digit decimal number from API in Kotlin?

I'm getting a price value from an API but it's a multi-digits decimal number like 0.4785835398457. I want to reduce this number to 3 or 4 digits number like 0.3234 and I'm showing that value in a TextView. So First, I have to form this value and second I need to convert it to String. I tried that DecimalFormat method like at onBindViewHolder part of my RecyclerAdapter.
override fun onBindViewHolder(holder: CoinListViewHolder, position: Int) {
val df = DecimalFormat("#.###")
df.roundingMode= RoundingMode.CEILING //<-----Here
df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() }) // <----- And here
holder.itemView.coinTicker.text= coinList[position].asset_id
holder.itemView.setOnClickListener {
listener.onItemClick(coinList, position)
}
But it did not work. Please help me.
Thanks in advance.
You can just use a string formatter that uses the number of decimal places you want:
val number = 123.12345
"%.3f".format(number).run(::println)
>> 123.123
That basically converts a float value (f) to a string, to three significant digits (.3). The format spec is here but it's a bit complex.
As far as your code goes, this:
df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() })
is equivalent to this:
val price = coinList[position].price_usd
holder.itemView.coinPrice.text = price.toString()
df.format(price)
I'm assuming you want to format the price and then display it in the TextView (right now you're just formatting it and doing nothing with the result), which would be this:
df.format(coinList[position].price_usd)
.let { holder.itemView.coinPrice.text = it.toString() }
i.e. do the format, and then do this with the result
Try holder.itemView.coinPrice.text = df.format(coinList[position].price_usd)

String "2" toInt returns 50

Im just working through some simple practice problems in kotlin. In my code below I'm taking a number and attempting to add the number members together. Ex. 29, return 2 + 9 = 11. There could be a better way to accomplish this but, I'm taking the numbers, converting to string, and then putting them into a list, ie ["2","9"] when I attempt to convert list[0].toInt() it returns 50. It appears there is some rounding taking place but I have not found another kotlin method to work with. Can anyone offer some insights? TIA
fun main(args: Array<String>) {
fun addTwoDigits(n: Int): Int {
val sliced = n.toString().toList()
val int1 = sliced[0].toInt()
println(sliced[0]) //returns "2"
println(int1) // returns 50
return sliced[0].toInt() + sliced[1].toInt()
}
println(addTwoDigits(29))
}
Koltin Char.toString(), which you are using in line:
val int1 = sliced[0].toInt()
converts the character using the ASCII Code table.
You can simply add a toString() call before the toInt() call:
val int1 = sliced[0].toString().toInt()

Extract value out of Kotlin arrow Either type and assign it to const

It would be a basic question, but I couldn't figure out a solution. I need to initialize a constant out of the right-side value of below either type.
val test: Either<String, Int> = 1.right()
I tried something like below but it shrinks the scope of the constant.
when(test) {
is Either.Right -> {val get:Int = test.b}
is Either.Left -> println(test.a)
}
I want that get to be scoped outside of when statement. Is there any way to do it or Arrow Either is not made for this purpose?
The important question is: what should happen if the Either is Left. In this example it is created close to where it's used, so it is obvious to you as a developer. But to the compiler what is inside the Either can be either an Int or a String.
You can extract the value using for example fold:
val x = test.fold({ 0 }, {it}) // provide 0 as default in case the Either was a `Left`
// x = 1
another option is getOrElse
val test = 1.right()
val x = test.getOrElse { 42 } // again, default in case it was a `Left`
// x = 42
You can also work with it without unwrapping it:
val test = 1.right()
val testPlus10 = test.map { it + 10 } // adds 10 to `test` if it is `Right`, does nothing otherwise
val x = testPlus10.getOrElse { 0 } // unwrap by providing a default value
// x = 11
For more example check the official docs.
Recommended reading: How do I get the value out of my Monad

How can I get the value of a T-student distribution?

I have been reviewing the documentation of apache commons math and I find that it also calculates distributions, but I can not understand how it works.
I have two values
degrees of freedom = 13
confidence interval = 0.95
My problem is that it does not yield the value I need,
The objective is:
result = 1.771
import org.apache.commons.math3.distribution.TDistribution
fun calculo(a:Double, b:Double): Double {
val distf = TDistribution(a,b)
return distf.getNumericalMean()
}
fun main(args: Array<String>) {
val ko = calculo(13,0.95)
println(ko)
}
```
You can use the following:
new org.apache.commons.math3.distribution.TDistribution(deg_freedom).
inverseCumulativeProbability(probability)
Where deg_freedom=13, and probability=0.95.

Kotlin Long to Float difference

I am trying to convert Long value to Float in Kotlin. However I am seeing it is changing the value by a small fraction.
Here's a simple test run:
import java.text.DecimalFormat
fun main(args: Array<String>) {
val l = 1513741500
val f:Float = l.toFloat()
val df = DecimalFormat("0")
println(df.format(f))
}
Output:
1513741440
As can be seen there is a slight difference between the values. How can I ensure the same value is returned on conversion?
l: Int = 1513741500
f: Float = 1.51374144E9
d: Double = 1.5137415E9
So if you plan to use large numbers, rather use Double than Float.