0

How to convert an Integer or a String number to a float number like this "1" to 1.0f (or 1f). I tried most of all codes, but all time I get the same. But, I need to get 1f.

val num = 1
val b = num.toFloat()
Log.i("b",b.toString())

Result is 1.0.

Azeem
  • 7,659
  • 4
  • 22
  • 36
deepthi
  • 1
  • 1

2 Answers2

1

By adding toFloat() to num, you have converted num to from an int to float. Kotlin also allows you to convert to float using conventional notation that is by adding f or F at the end of 1

val num = 1f

or

val num = 1F

To print out the float with the trailing 'f', you can convert the float to a string and add a "f".

val num = 1F
print(num.toString() + "f") // Result = 1.0f

To print out just 1f, you don't need to convert it to a float.

val num = 1
print(num.toString() + "f")
Alf Moh
  • 6,849
  • 5
  • 37
  • 48
-4

You can find your answer here: convert float to string.

float f = Float.parseFloat("1");

This case works for a string. For ints, cast the value:

int val = 1;
float f = (float) val;
Maxime Franchot
  • 815
  • 7
  • 20
  • @ChristianBrüggemann My bad.. I didn't pay attention and I don't know this language. But it does clearly say in the title and in the tags "Java", which is what confused me – Maxime Franchot Jul 22 '17 at 01:47