Pengkategorian Hasil BMI

This commit is contained in:
202310715297 RAIHAN ARIQ MUZAKKI 2025-11-06 23:30:23 +07:00
parent 59db5c2b0c
commit b5db44764b

View File

@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
import com.example.bmicalculator.ui.theme.BMICalculatorTheme import com.example.bmicalculator.ui.theme.BMICalculatorTheme
import java.text.DecimalFormat import java.text.DecimalFormat
import java.text.NumberFormat import java.text.NumberFormat
import java.util.Locale
import kotlin.math.pow import kotlin.math.pow
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
@ -100,7 +101,7 @@ fun BMICalculatorLayout() {
val BmiHeight = heightInput.toDoubleOrNull() ?: 0.0 val BmiHeight = heightInput.toDoubleOrNull() ?: 0.0
val BmiWeight = weightInput.toDoubleOrNull() ?: 0.0 val BmiWeight = weightInput.toDoubleOrNull() ?: 0.0
val bmi = calculateBMI(BmiHeight, BmiWeight, unitUSC) val bmi = calculateBMI(BmiHeight, BmiWeight, unitUSC)
val category = calculateBMICategory(BmiHeight, BmiWeight, unitUSC) val category = calculateBMICategory(bmi)
Column( Column(
modifier = Modifier modifier = Modifier
@ -212,7 +213,7 @@ private fun calculateBMI(BmiHeight: Double, BmiWeight: Double, unitUSC: Boolean)
return "0" return "0"
} }
val heightInMeter = BmiHeight/100 // konversi centimeter ke meter val heightInMeter = BmiHeight/100 // konversi centimeter ke meter
var bmi = BmiWeight / heightInMeter.pow(2) var bmi = BmiWeight / heightInMeter.pow(2)
if (unitUSC == true) { if (unitUSC == true) {
@ -224,17 +225,25 @@ private fun calculateBMI(BmiHeight: Double, BmiWeight: Double, unitUSC: Boolean)
} }
/** /**
* Calculates the BMI Category * Calculates the BMI Category
* bmi < 18.5 -> Underweight
* 18.5 <= bmi < 25 -> Normal
* 25 <= bmi <= 30 -> Normal
* bmi > 30 -> Overweight
* *
* Catatan: tambahkan unit test untuk kalkulasi BMI ini * Catatan: tambahkan unit test untuk kalkulasi BMI ini
*/ */
private fun calculateBMICategory(bmi: String): String {
val bmiValue = bmi.replace(",", ".").toDoubleOrNull() ?: return ""
private fun calculateBMICategory(BmiHeight: Double, BmiWeight: Double = 15.0, unitUSC: Boolean): String { return when {
var bmi = BmiWeight / 100 * BmiHeight bmiValue == 0.0 -> ""
if (unitUSC) { bmiValue < 18.5 -> "Underweight"
bmi = kotlin.math.ceil(bmi) bmiValue < 25.0 -> "Normal"
bmiValue < 30.0 -> "Overweight"
else -> "Obesity"
} }
return NumberFormat.getNumberInstance().format(bmi)
} }
@Preview(showBackground = true) @Preview(showBackground = true)
@Composable @Composable
fun TipTimeLayoutPreview() { fun TipTimeLayoutPreview() {