I'm creating a currency application but some of values are like "194.23564" or "1187.7594" so i want to show the user before the "." sign values. How can i make this with Kotlin ?
There is no need for data type conversion before the extraction of the integer part.
You can use substringBefore():
val number = "194.23564"
val intPart = number.substringBefore(".")
If you want the result as an integer number you can use now toIntOrNull(), instead of toInt(), so to avoid an exception in case the initial string has no integer part (like ".015"):
val intPart = number.substringBefore(".").toIntOrNull()
Other than suggested, I would not convert to Float. This is susceptible to rounding errors and may not return the value before the decimal point.
Example:
val num = "0.99999999"
println(num.toFloat().toInt()) // gives 1
Instead, split the string at the decimal point:
val num = "0.99999999"
val split = num.split('.')
println(split[0]) // gives 0
A nice side effect of this implementation is that it even works for integral numbers without a decimal point. If you need the result as an Int, simply call split[0].toInt().
There is no need to use float in this case. If you want to get the value before ".", you need to use int instead of float. When you use float you will get value in points, but when you use int, you will get the value before ","
Related
I have encountered a problem when handling floats in an Android application
My case regards handling decimal places in kotlin Float, but I think it can be applied to Java.
Let's assume that I have an EditText which is a Number field in an Android app. This way, an user can just input an integer, and by an integer I mean a whole number, not the primitive data type. It's then passed to the code as a String so it doesn't matter.
private lateinit var weightText: EditText
private lateinit var heightText: EditText
Let's say that the user inputs two numbers - 120 and 174.
weightText = findViewById(R.id.etWeight)
heightText = findViewById(R.id.etHeight)
Then I am making an Body Mass Index calculation on them:
val bmiEquals = weight.toFloat() / ((height.toFloat() / 100) * (height.toFloat() / 100))
Easy.
But bmiEquals in this case is equal to 38.73967
Now I'd like to display the user this number with just two decimal places: 38.74
To achieve this I do:
val df = DecimalFormat("#.##")
val bmi2Digits = df.format(bmiEquals)
It was working fine in the Android emulator, but when I've tested the code on my physical device, I've encountered a problem here:
private fun displayResult(bmi: String) {
when (bmi.toFloat()) {
I got an error cause bmi variable was not 38.74 but 38,74. I have researched a bit and it seems that this is caused by locale. In some countries, you divide floating point numbers using a dot, in some others - a comma. And DecimalFormat is used to format a number to a String.
I know that I could just use BigDecimals here, but I wonder if there is any way to handle this case while working on Floats.
Honestly? I have solved this problem using a silly solution:
when (bmi.replace(',', '.').toFloat()) {
But it is bothering me so hard... ;)
you may always check which character is an decimal separator on running device using
DecimalFormatSymbols.getInstance().getDecimalSeparator()
You may use DecimalFormat with a specific locale.
val bmiEquals = 38.73967
Locale.setDefault(Locale.FRENCH)
val dfUS = DecimalFormat("#.##", DecimalFormatSymbols(Locale.US))
// or df.decimalFormatSymbols = DecimalFormatSymbols(Locale.US)
val dfResultUS = dfUS.format(bmiEquals)
println(dfResultUS) // output: 38.74
val dfLocale = DecimalFormat("#.##")
val dfResultLocale = dfLocale.format(bmiEquals)
println(dfResultLocale) // output: 38,74
try following round functionality from import kotlin.math.round
var bmi2Decimal = round(bmiEquals * 100)/100
bmi2Decimal is float and in this case, 100 is used to make it 2 decimal place
val userInput:Int = -0
fun costumPrint(x:Int){ println(x) } // = 0 <- not i want , -0 <-is what i want
how can i print/get exatly what in userInput (with negative sign) but keep using integer as parameter
Kotlin (JVM, and generally most) Integers, do not have positive and negative zero.
Some other people have noted Strings, but maybe a Float or Double would suit your use case, as those have 2 values of 0. Note that that would be very hacky and I discourage you, so probably just go for strings
Mostly, I use Int, Double and String, Char. Recently, I got interested in saving memory and I realized even small amount of bytes can be much larger and it affects the program and even the mobile speed and battery life.(Especially, data resources of its memory)
So, I am trying to use Byte, Short when the data doesn't need to store big numbers. For example, byte for -128 ~ 127, Short for -32,768 ~ 32,767.
Is it a good idea?
And My main question is I want to know the data type of const val in Kotlin since it automatically defines the datatype.
const val THIS_IS_STRING = "HelloWorld"
const val THIS_IS_CHAR = 'C'
const val NUMBER_1 = -124
const val NUMBER_2 = 31000
const val NUMBER_3 = 1000000
const val NUMBER_4 = 1232188777777344444
const val NUMBER_5 = 29128812312732881231273712
const val NUMBER_6 = 0.423
const val NUMBER_7 = 0.2121222222441
const val NUMBER_8 = 0.813881281237123991827312324
const val NUMBER_9 = 0.5123090982307037412398190092340239423094803820432423423209823092342342348209384023984023480923840923840009930923094029848901
What are the data types of them(The numbers)?
Or should I define like these for saving the resources? Or I don't need to?
const val MIN:Byte = -124
const val MID:Short = 31000
const val MAX:Int = 1000000
...
``
It is dependent on you whether you want to provide data type allocation to kotlin or self. If your saving the values by providing resource type. You can save data or you can depend on the kotlin.
But if your saving the data i will advice you to provide the data type :
Let's take this as an example for you :
fun main() {
var b: Any = 124
println(b)
if(b is Float) {
println("Float")
}
else if(b is Double) {
println("Double")
}else if(b is Byte){
println("byte")
}else if(b is Int){
println("int")
}else if(b is Short){
println("short")
}
}
It will provide the output as Int.
So i suggest provide data type.
Type inference is described in https://kotlinlang.org/docs/reference/basic-types.html
Basically the default types when not specified for a number in range of -231 to 231-1 is Int and higher than that is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for Byte and Short.
val one = 1 // inferred as Int
val threeBillion = 3000000000 // inferred as Long
val oneL = 1L // explicitly specify Long type by appending with L
val oneLong: Long = 1L // explicitly specify Long by type
val oneByte: Byte = 1 // explicitly specify Byte for saving memory
For floating point numbers default type is Double, you can switch to float by either specifying type or appending f.
val pi = 3.14 // Double
val piFloat: Float = 3.14 // explicitly specify Float by type
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // explicitly specify Float by appending with f
The characters and strings by nature having single data type so it is Char and String by default, and there is no need to change it explicitly.
It is generally Advisable to specify types to save memory because it is constant and will never change so conservation is a better choice, but it is all upto you.
Kotlin Type inference - In Kotlin most of the time, you won't need to specify the type of the objects you are working with, as long as the compiler can infer it.
So, we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly as well. Say, for instance, you define val REQUEST_CODE = 100. Behind the scenes, REQUEST_CODE initializes with the Int datatype since the value of REQUEST_CODE is of type Int, the compiler infers that REQUEST_CODE is also a Int. Note that Kotlin is a statically-typed language. This means that the type is resolved at compile time and never changes.
Although Kotlin uses Type Inference ( automatically identify something ), which means we also have the option to specify the data type when we initialize the variable like below:
val REQUEST_CODE: Int = 100
Both act the same while converting it to byte code.
What the heck, How do Kotlin determine the data type of numbers if we
use implicit declaration?
Good question, Kotlin provides a set of built-in types that represent numbers. For integer numbers, there are four types with different sizes and, hence, value ranges.
All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int. If the initial value exceeds this value, then the type is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for data types like Byte & Short as mentioned by Animesh in the accepted answer.
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
Reference
https://kotlinlang.org/docs/reference/basic-types.html
I’m surprised there are so many answers here ignoring this, but using Byte and Short for properties will not save you memory. The backing variables still take up 4 bytes of memory for each. They only save you memory when you use them in ByteArray and ShortArray. They also can cause a performance penalty for doing arithmetic with them instead of Int or Long, but that’s insignificant in most applications.
As other answers have mentioned Int is implicit unless the number is big enough to be a Long. And this is what you want because it is more performant and takes up the same amount of memory.
Const is a compilation time constant. This means that a value must be allocated during the compilation time, unlike the value that can be performed at run-time, meaning that the const cannot be assigned to a function or class constructor and should only be allocated as character series or basic data type.
I am getting an integer value in my android application.I want to convert it into floating point number which is in this format
"0.xyF"
.I tried lot of methods.I know its simple but i am confused.Please help.
I am passing a value from one activity to another using putExtra.So in the second activity i have to convert it to float for setting the value as verticalMargin for my dialog window.I used this line for getting the value in second activity.
int data = getIntent().getIntExtra("value", 7);
This is used for setting the vertical margin.
wlp.verticalMargin = "the converted floating point number";
If i is the integer value, then try:
float f=i;
while(f>=1.0f)
f/=10.0f;
You question still isn't clear. If you're asking how to convert an integer value that represents a percentage from 0 to 100 into a floating point value, then it would be fpVal = intVal / 100.0;
If you just want a simple conversion of an integer into a floating point number with the same exact value (e.g. 7 --> 7.0), then you can just cast it: fpVal = (float) intVal;
In your first activity store your integer value in string like this
String margin = "0."+int_value;
then pass this string to second activity.
In the second activity get that string from extra and convert it to float.
float float_value = Float.parseFloat(margin);
I need calculate a thing. but my formula sentence has occur some problem.
TextView ticketP = (TextView)findViewById (R.id.ticketQ);
ticketP.setText(oneSession.getTicketOder());
String Ctotal = "";
Ctotal = jsonObject.optString("price");
String OneTotal = oneSession.getTicketOder() * Ctotal; // this part has occur the problem which is the operator * .
You'll need to convert the Strings to numeric type before performing any multiplication. Depending on the type of numeric value you are using take a look Double.parseDouble(String string) or Integer.parseInt(String string).
int oneTotal = Integer.valueOf(oneSession.getTicketOder()) * Integer.valueOf(Ctotal);
to convert it again to String use
String.valueOf(oneTotal)
Yes. Your going to have to use the parsing methods in order to convert the string to a native numerical type. You also need to be care about a few things with your code.
json.optString() can return null. opt = optional.
I would suggest using json.getInt() or json.getDouble() this will not only give you the correct type, but also throw an exception if the values aren't correct.
Secondly your going to have to convert your numerical answer back to a string if you want to display it. But this is easy enough with a .toString() or + "" if you are lazy.