baeldung-articles : BAEL-7180 (#15616)

Check if a float value is equivalent to an integer value in Java.
This commit is contained in:
DiegoMarti2 2024-01-14 00:38:34 +02:00 committed by GitHub
parent 680ebf45a7
commit f75ab1c847
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 64 additions and 0 deletions

View File

@ -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);
}
}