In Android-Kotlin I am getting float number from backend (for example num = 10000000.47)
When I try to String.format it and add that number in my balanceTextview it shows it with exponent (something like 1.0E10).
I want to show number normally without exponent and with 2 decimals. (Without presicion loss!)
Tried to use DecimalFormat("#.##") but it didn't help me. Maybe I'm doing something wrong?
num = 10000000.47f
val dec = DecimalFormat("#.##")
var result = dec.format(num)
my result is: 10000000
It losts my decimal places
The issue is your number type. According to the documentation:
For variables initialized with fractional numbers, the compiler infers the Double type. To explicitly specify the Float type for a value, add the suffix f or F. If such a value contains more than 6-7 decimal digits, it will be rounded.
With an example that shows how information may get lost:
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
If the value is specified as Double instead of Float, i.e.
val num = 10000000.47
instead of
val num = 10000000.47f
then your approach works as expected, but could be shortened to:
"%.2f".format(num)
(note that the shorter version will also print "100" as "100.00" which is different from your approach but potentially still desired behaviour)
If you receive a Float from the backend then the information is already lost on your side. Otherwise you should be able to fix the issue by improved parsing.
The extension function format is only available in the JVM. In Kotlin/native, you can use this instead:
fun Float.toPrecision(precision: Int) =
this.toDouble().toPrecision(precision)
fun Double.toPrecision(precision: Int) =
if (precision < 1) {
"${this.roundToInt()}"
} else {
val p = 10.0.pow(precision)
val v = (abs(this) * p).roundToInt()
val i = floor(v / p)
var f = "${floor(v - (i * p)).toInt()}"
while (f.length < precision) f = "0$f"
val s = if (this < 0) "-" else ""
"$s${i.toInt()}.$f"
}
Related
I have this code that keeps giving me a "Val cannot be reassigned" error but I can't seem to change the variable to a var instead of val. I simply want to be able to set a string value to my cell reference so I can access the values later like this myStringsArrayList.add(deviceData.cellOne).
Here is my code:
val cells = listOf(
deviceData.cellOne,
deviceData.cellTwo,
deviceData.cellThree,
deviceData.cellFour,
deviceData.cellFive,
deviceData.cellSix,
deviceData.cellSeven,
deviceData.cellEight,
deviceData.cellNine,
deviceData.cellTen,
deviceData.cellEleven,
deviceData.cellTwelve,
deviceData.cellThirteen,
deviceData.cellFourteen
)
for ((i, cell) in cells.withIndex()) {
val value = data[2 + i].toDouble() / 100 + 3.52
val cellNumberString = (i + 1).toString()
val formattedString = "Cell $cellNumberString: %.2fV".format(value)
cell = formattedString // THIS IS WHERE THE PROBLEM IS (cell is a val)
}
Does anyone know how I can get around this and achieve the functionality that I want?
I tried using a listIterator() but it hasn't seemed to work the way that I want it to.
Here is my attempt with the listIterator():
val cells = mutableListOf(
deviceData.cellOne,
deviceData.cellTwo,
deviceData.cellThree,
deviceData.cellFour,
deviceData.cellFive,
deviceData.cellSix,
deviceData.cellSeven,
deviceData.cellEight,
deviceData.cellNine,
deviceData.cellTen,
deviceData.cellEleven,
deviceData.cellTwelve,
deviceData.cellThirteen,
deviceData.cellFourteen)
val iterate = cells.listIterator()
while (iterate.hasNext()) {
var cell = iterate.next()
val value = data[2 + iterate.nextIndex()].toDouble() / 100 + 3.52
val cellNumberString = (iterate.nextIndex() + 1).toString()
val formattedString = "Cell $cellNumberString: %.2fV".format(value)
cell = formattedString
}
You can't make that a var, and there's no reason to anyway!
for ((i, cell) in cells.withIndex()) {
...
cell = formattedString // THIS IS WHERE THE PROBLEM IS (cell is a val)
}
You're creating a for loop there on a collection, with an index, and giving it a block of code to run for each loop. So when the loop runs, you're provided with two parameters - the current item from the collection, and its index in that collection.
These are just internal variables for use in the loop - you can't reassign them, because they're the values being passed in. Even if you could, you'd just be changing the values of those local variables.
What you're probably trying to do is update the cells list, taking the current item in the loop, finding it in cells, and replacing it. You'd have to actually update cells to do that! Change the list itself. You could do that with cells[i] = formattedString - but because you're currently iterating over that cells collection, you shouldn't modify it!
You could copy the source list, but the typical Kotlin way is to create a new list, using map (which transforms values):
cells.mapIndexed { i, cell ->
val value = data[2 + i].toDouble() / 100 + 3.52
val cellNumberString = (i + 1).toString()
// last expression is the return value, i.e. the formatted string
"Cell $cellNumberString: %.2fV".format(value)
}
That will spit out a new (immutable) list where each cell has been mapped to that formatted string version.
You could make cells a var and just reassign it:
cells = cells.mapIndexed { ... }
or just chain the map call when you initialise the val, so that end result is what gets assigned:
val cells = listOf(
...
).mapIndexed { ... }
But you're not actually using cell in that loop anyway, just using the index to generate values. You can create a list like this:
val data = List(14) { i ->
val value = data[2 + i].toDouble() / 100 + 3.52
// you can calculate the index inside the string by using braces
"Cell ${i + 1}: %.2fV".format(value)
}
It all depends whether you need to keep that list of devicedata values around for anything (if so use it to create another list)
You may wanna use Interator this way:
val list = mutableListOf("One", "Two", "Three", "Four")
println(list.joinToString(" "))
val iterator = list.listIterator()
while(iterator.hasNext()) {
val value = iterator.next()
if (value == "Two") {
iterator.set("xxxxxx")
}
}
println(list.joinToString(" "))
Use the 'set' method.
I have a simple problem for which I didn`t find a solution. I am having large negative number ex(-6763.98) what I want is something like this ex($-6.78K). A found a lot of solutions that work for positive numbers but none that work for negative. This is the code that I am having right now.
const val COUNT_DIVISOR = 1000
const val COUNT_DIVISOR_FLOAT = 1000.0
fun getFormattedNumber(count: Long): String {
if (count < COUNT_DIVISOR) return "" + count
val exp = (ln(count.toDouble()) / ln(COUNT_DIVISOR_FLOAT)).toInt()
return resources.getString(
R.string.decimal_format_long_number_price,
count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble()), EXTENSION[exp - 1]
)
}
The natural logarithm is not defined for negative values so the function ln will return NaN (not a number) for negative inputs.
From ln Kotlin documentation.
Special cases:
ln(NaN) is NaN
ln(x) is NaN when x < 0.0
ln(+Inf) is +Inf
ln(0.0) is -Inf
You have to make sure that the input is always a positive value in order to calculate the exponent correctly.
val exp = (ln(abs(count.toDouble())) / ln(COUNT_DIVISOR_FLOAT)).toInt()
Another problem is the first if check, which returns the input value itself for all inputs smaller than COUNT_DIVISOR. You have to allow large negative inputs through there as well.
if (count > -COUNT_DIVISOR && count < COUNT_DIVISOR) return "" + count
All together
const val COUNT_DIVISOR = 1000
const val COUNT_DIVISOR_FLOAT = 1000.0
fun getFormattedNumber(count: Long): String {
if (count > -COUNT_DIVISOR && count < COUNT_DIVISOR) return "" + count
val exp = (ln(abs(count.toDouble())) / ln(COUNT_DIVISOR_FLOAT)).toInt()
return resources.getString(
R.string.decimal_format_long_number_price,
count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble()), EXTENSION[exp - 1]
)
}
If you want the result to always have 2 decimal places, consider any of these
val result = count / COUNT_DIVISOR_FLOAT.pow(exp.toDouble())
// This will use the root language/region neutral locale
// it will use the dot '.' as the decimal separator
"%.2f".format(Locale.ROOT, result)
// This will use the default locale
// it will use '.' or ',' as the decimal separator, based on the user settings on the target system
"%.2f".format(result)
val localeDefinedByYou = ... // or define a specific locale
"%.2f".format(localeDefinedByYou, result)
I am writing an instrument tuner app (for now starting with Guitar). For pitch detection I'm using TarsosDSP. It does detect the pitch correctly, however it is quite shaky - for example, I'll hit the (correctly tuned) D string on my Guitar, it correctly recognizes it as a D, but after a short moment it cycles through a bunch of random notes very quickly. I'm not sure how to best solve this. Here is my code which is responsible for detecting the pitch:
val dispatcher: AudioDispatcher = AudioDispatcherFactory.fromDefaultMicrophone(44100, 4096, 3072)
val pdh = PitchDetectionHandler { res, _ ->
val pitchInHz: Float = res.pitch
runOnUiThread { processing.closestNote(pitchInHz)}
}
val pitchProcessor: AudioProcessor =
PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN,
44100F, 4096, pdh)
dispatcher.addAudioProcessor(pitchProcessor)
val audioThread = Thread(dispatcher, "Audio Thread")
audioThread.start()
I have then written a function which is supposed to detect the closest note to the current pitch. In addition I tried to get the results "less shaky" by also writing a function which is supposed to find the closest pitch in hz and then using that result for the closestNote function thinking that this way I may get less different results (even though it should be the same, and I also don't notice any difference). Here are the two functions:
...
private val allNotes = arrayOf("A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#")
private val concertPitch = 440
...
/** detects closest note in A = 440hz with with equal temperament formula:
* pitch(i) = pitch(0) * 2^(i/12)
* therefore formula to derive interval between two pitches:
* i = 12 * log2 * (pitch(i)/pitch(o))
*/
fun closestNote(pitchInHz: Float) {
(myCallback as MainActivity).noteSize() //adjusts the font size of note
if (pitchInHz != -1F) {
val roundHz = closestPitch(pitchInHz)
val i = (round(log2(roundHz / concertPitch) * 12)).toInt()
val closestNote = allNotes[(i % 12 + 12) % 12]
myCallback?.updateNote(closestNote) // updates note text
}
}
private fun closestPitch(pitchInHz: Float): Float {
val i = (round(log2(pitchInHz / concertPitch) * 12)).toInt()
val closestPitch = concertPitch * 2.toDouble().pow(i.toDouble() / 12)
return closestPitch.toFloat()
}
Any ideas how I can get more consistent results? Thanks!
Solved it myself: TarsosDSP calculates a probability with every note being played. I set my closestNote function to only update the text if the probability is > 0.91 (I found that value to offer "stability" in terms of text not changing after hitting a string and still correctly recognizing the note without hitting the string multiple times/too hard, also tested it with an unplugged, non hollow body electric Guitar)
I have String with decimal points of value. When I convert the String value to Float like this
val i : String = "123.70"
val j = i.toFloat()
Log.e("Tag", "-->" + j)
the result printed is
Tag-->123.7
But, what I want is
Tag-->123.70
Is there any possible way to get my desired result?
You can simply use a String that takes a decimal and formats it to a specific amount of decimal places.
Example:
fun main() {
// you have a String with a decimal value
val i : String = "123.70"
// then you parse/convert it to a Float
val j : Float = i.toFloat()
// and then, you output the value of the Float in a specific format
println("%.2f".format(j))
}
This prints
123.70
which should be working in the LogCat as well:
Log.e("Tag", "-->%.2f".format(j))
internally it doesn't affect it is the same but if you want to show it as 2 decimal places you can use String.format("%.2f", number).
val number = 10.7086134
val rounded = String.format("%.3f", number) // rounds to 3 decimal places
I am summing double value from arraylist its giving additional decimals as 99999, how to fix this, please guide
ex
class ExDet{var expName:String ="",var expAmount:Double = 0.0}
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
Expected Value of Amount is :
Amt = 857.45
But it returns
Amt = 857.4499999
Sample Code to Test
data class ExDet(var expName:String ="" ,var expAmount:Double=0.0)
fun main(args: Array<String>) {
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
println("Amount is : $amt")
}
The issue you are confronted with is that floating point numbers are build on top of base 2, not base 10.
Think how you can easily represent a third as a fraction (1/3), but when you convert to decimal you get a repeating (recurring) number after the radix point (i.e. 0.33...). Some decimal numbers are recurring when represented in base-2, e.g. x.9. The computer has a finite number of bits, so the (base-2) number is truncated. All the truncation errors can add up.
You need to round to the required precision (e.g. round(x * 100) / 100).
If you are only interested in how it is displayed then you can use the format function with something like "%.2f".
String.format("%.2f", value)