How to convert a float to int in your Android App?

In this video it shows that how Math.round method can be used to convert the float number to the nearest integer number by rounding operation.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Complete source code:

package com.programmerworld.floattoint;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private EditText editTextFloat;
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextFloat = findViewById(R.id.editTextNumberDecimal);
textView = findViewById(R.id.textView);
}

public void buttonConvertFloatToInt(View view){
Float floatInput = Float.valueOf(editTextFloat.getText().toString());
int intOutput = Math.round(floatInput);

textView.setText(String.valueOf(intOutput));
}
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="209dp"
android:layout_height="68dp"
android:text="Hello World!"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editTextNumberDecimal"
android:layout_width="267dp"
android:layout_height="93dp"
android:layout_marginStart="65dp"
android:layout_marginTop="51dp"
android:ems="10"
android:hint="Enter Float number here..."
android:inputType="numberDecimal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="84dp"
android:layout_marginTop="56dp"
android:onClick="buttonConvertFloatToInt"
android:text="Convert Float to Int"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextNumberDecimal" />

</androidx.constraintlayout.widget.ConstraintLayout>

Leave a Reply

%d bloggers like this:
Available for Amazon Prime