+ 2

How to know number after point in c#

I need to check are there floats that ends with .0 and convert them to integers. How can I do that? For example if a = 2.0, i need to find that float and turn it to integer - a = 2?

6th Jan 2024, 3:04 PM
Ruben Melikyan
Ruben Melikyan - avatar
7 ответов
+ 8
You should share your attempt if you would like help debugging your code. Because you have not here is a hint: I would probably start by rounding the float and compare the original float with it's rounded counterpart to test if they are the same. This would mean the float number ends in '.0' and should be converted to an integer.
6th Jan 2024, 3:28 PM
Keith
Keith - avatar
+ 6
You could explicitly convert one type of number to another, you use a cast. That's the parentheses before the number with the type of the number that you want to convert it to. Note that the fractional part of the floating-point number will be dropped. float a = 2.3f; int b = (int)a; // 2
6th Jan 2024, 4:20 PM
JaScript
JaScript - avatar
+ 4
1. First convert the double to integer 2. Check if the value is the same as previous or no If it is: use the converted version. If it isn't: use the original version.
6th Jan 2024, 10:32 PM
🇮🇱 Radin Masiha 🇮🇱
🇮🇱 Radin Masiha 🇮🇱 - avatar
6th Jan 2024, 11:58 PM
Bob_Li
Bob_Li - avatar
+ 3
if (a == ((int) a)) is True, then the float or double is equal to the same number cast to integer, so in this case it is safe to convert.
7th Jan 2024, 5:55 AM
Tibor Santa
Tibor Santa - avatar
+ 2
In C#, you can check if a float ends with ".0" and convert it to an integer using a simple condition. Here's an example: ```csharp using System; class Program { static void Main() { float a = 2.0f; // Check if the float ends with ".0" if (a % 1 == 0) { // Convert float to integer int intValue = (int)a; // Output the result Console.WriteLine(
quot;Original float: {a}"); Console.WriteLine(
quot;Converted integer: {intValue}"); } else { Console.WriteLine("Float does not end with '.0'"); } } } ``` In this example, the condition `a % 1 == 0` checks if the float `a` has no fractional part, which is indicative of ending with ".0". If the condition is true, it means `a` is effectively an integer, and you can safely cast it to an `int` using `(int)a`.
8th Jan 2024, 2:24 AM
𝐀𝐲𝐞𝐬𝐡𝐚 𝐍𝐨𝐨𝐫
𝐀𝐲𝐞𝐬𝐡𝐚 𝐍𝐨𝐨𝐫 - avatar
+ 1
Ok thanks, I will try it
6th Jan 2024, 3:31 PM
Ruben Melikyan
Ruben Melikyan - avatar