From f75ab1c847bd964a194eb04490a6eceb688ddddd Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Sun, 14 Jan 2024 00:38:34 +0200 Subject: [PATCH] baeldung-articles : BAEL-7180 (#15616) Check if a float value is equivalent to an integer value in Java. --- ...eckIfFloatEquivalentToIntegerUnitTest.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/checkiffloatequivalenttointeger/CheckIfFloatEquivalentToIntegerUnitTest.java diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/checkiffloatequivalenttointeger/CheckIfFloatEquivalentToIntegerUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/checkiffloatequivalenttointeger/CheckIfFloatEquivalentToIntegerUnitTest.java new file mode 100644 index 0000000000..e9a4705061 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/checkiffloatequivalenttointeger/CheckIfFloatEquivalentToIntegerUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.checkiffloatequivalenttointeger; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.util.Scanner; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CheckIfFloatEquivalentToIntegerUnitTest { + float floatValue = 10.0f; + + @Test + public void givenFloatAndIntValues_whenCastingToInt_thenCheckIfFloatValueIsEquivalentToIntegerValue() { + int intValue = (int) floatValue; + + assertEquals(floatValue, intValue); + } + + @Test + public void givenFloatAndIntValues_whenUsingTolerance_thenCheckIfFloatValueIsEquivalentToIntegerValue() { + int intValue = 10; + float tolerance = 0.0001f; + + assertTrue(Math.abs(floatValue - intValue) <= tolerance); + } + + @Test + public void givenFloatAndIntValues_whenUsingFloatCompare_thenCheckIfFloatValueIsEquivalentToIntegerValue() { + int intValue = 10; + + assertEquals(Float.compare(floatValue, intValue), 0); + } + + @Test + public void givenFloatAndIntValues_wheUsingRound_thenCheckIfFloatValueIsEquivalentToIntegerValue() { + int intValue = 10; + + assertEquals(intValue, Math.round(floatValue)); + } + + @Test + public void givenFloatAndIntValues_whenUsingScanner_thenCheckIfFloatValueIsEquivalentToIntegerValue() { + String input = "10.0"; + Scanner sc = new Scanner(new ByteArrayInputStream(input.getBytes())); + + float actualFloatValue; + if (sc.hasNextInt()) { + int intValue = sc.nextInt(); + actualFloatValue = intValue; + } else if (sc.hasNextFloat()) { + actualFloatValue = sc.nextFloat(); + + } else { + actualFloatValue = Float.NaN; + } + + sc.close(); + + assertEquals(floatValue, actualFloatValue); + } + +}