[C# Solution] Rounding

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
I have finally created my first prototype program in C#. Please report any problems. :)

The only thing I want to fix is: How do you round a float number?

Only works with integers at the moment.

And I'm thinking of creating some C# solution series in this forum. Not only I can improve my programming skills, but also can give help to those who view these posts. Here's the code in its glorious moments:

Note: To view the improved code, click here.

Code:
using System;

namespace Practice 
{
    public class Lesson_1 //Rounding a number to some places.
    {
        public void Rounding() 
        {
            int number, Place;
            Console.Write("Enter a value needed to be rounded: ");
            number = Int32.Parse(Console.ReadLine());
            Console.Write("How many places do you want to round [100: hundreds place, 10: tens place, 1: ones place, etc.]: ");
            Place = Int32.Parse(Console.ReadLine());

            CreatingEnvironment(number, Place);
        }

        private void CreatingEnvironment(int number, int Place)
        {
            int Condition = number % Place;
            if (Condition >= Convert.ToInt32(Place * 0.5))
            {
                number = (number + Place) - Condition;
            }
            else 
            {
                number = number - Condition;
            }
            Console.WriteLine("{0}", number);
        }   
    }

    class MainComponents 
    {
        public void Run() 
        {
            Lesson_1 StartingPoint = new Lesson_1();
            StartingPoint.Rounding();
        }

        static void Main() 
        {
            MainComponents Initializer = new MainComponents();
            Initializer.Run();
        }
    }
}
 

Xienoph

You can change this now in User CP.
Reaction score
43
Can't you just use the inbuilt rounding function? It's usually Math.round. If you want to round to 100s, divide the number by 100, round it, then multiply it by 100 again.

As for your code, some of the variable names are unclear / misleading. For example, when I saw "CreatingEnvironment", I thought that that method is ran at the start of the program and sets up the environment used to run the rest of the program. Not actually running the meat of the program.

Also, "Condition" doesn't really make sense. Maybe you're looking for something like ... "modValue"?

How do you decide which local variables should be capitalized? Normally, capitalized words mean public methods. This probably doesn't really matter in other languages, since method calls are followed by parenthesis, but in C#, you have an accessor, and using capitalized local variables can make people think that you're using an accessor.

You probably want to sanitize the input for Place. What if the user inputs "352"?
 

Vestras

Retired
Reaction score
249
I'd like to comment on your coding style, which is one of the most important things when programming: (note that this is just my opinion, but some of these are written standards for C# programming)
Code:
int number, Place;
No wai:

Code:
int number = 0;
int place = 0;

Note: C# variables should also start uncapitalized, e.g:

Code:
int place = 0;

or:

Code:
int placeAtTheMall = 0;

Code:
int Condition = number % Place;

Not very descriptive name, and it's capitalized:

Code:
int modValue = numer % place;

(Not really that descriptive either, but you get the point xD)

Code:
            if (Condition >= Convert.ToInt32(Place * 0.5))
            {
                number = (number + Place) - Condition;
            }
            else 
            {
                number = number - Condition;
            }

-->

Code:
            if (modValue >= Convert.ToInt32(place * 0.5))
                number = (number + Place) - Condition;
            else 
                number = number - Condition;

Also, it is general coding style that after a } comes a whitespace line, or after the end of a statement (e.g an else with no { and })

EDIT: oh, sorry, didn't read Xienoph's reply.
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
Well, I never had any C# courses in college, so I was just messing around, not knowing what to do. I never knew there's so many stuffs I got to learn...:( Guess I better learn from scratch.

Anyway, this is my first prototype, as mentioned in the my first post. It's version 0, so there's nothing wrong about that. I just learn everything from scratch, and just consulted a book called Learning C# from O'Reilly. So, it's just meaningless.

To Xienoph:

1. What math function? What is that stuff? I admit I never knew that stuff existed...
2. I don't know how to name those variables. I just threw them all in from my head.
3. The CreatingEnvironment() method was just the beginning. The program will improve later on, so the name is just a placeholder. What should I name it then?
4. Capitalized words means "public accessor"? What is that stuff? I really didn't learn that.
5. I'm just thinking of a concept right now for the Place. The sanitation will be in there in the future.

To Vestras:

1. Does the int part in the beginning really is part of the C# Standard?? Does C# Standards go with C++ Standards?
2. I thought variables use Pascal notations...
3. As for the variable names, I couldn't think of something that's descriptive. My vocabulary isn't good.
4. If...else: If I were to write just one statement in an if...else method, I don't need to use parentheses? in the Leaning C# book by O'Reilly, it said that even if there's just one statement, I must use parentheses to make it more readable...Is there something the book didn't say about it?

Thanks for the feedback guys! :thup:
 

GooS

Azrael
Reaction score
154
1. Does the int part in the beginning really is part of the C# Standard?? Does C# Standards go with C++ Standards?

Don't think he wanted you to write int on both, though it is more descriptive if you do, but more that he wanted you to initialize the variables (= 0), un-initialized ints, atleast i C++, get "random" values.

4. If...else: If I were to write just one statement in an if...else method, I don't need to use parentheses? in the Leaning C# book by O'Reilly, it said that even if there's just one statement, I must use parentheses to make it more readable...Is there something the book didn't say about it?

Well, no idea what O'Reilly says but if you see an if statement you know there's going to be atleast one statement in its scope, and if it has no curly bracers you know it can only be one statement in there. So I, and many others I believe, don't think it's a neccessity. If anything long if, else if, else sequences with only one statement in each scope and curly bracers around them all would clutter up alot of space.

But then again I shouldn't even comment on C# styling standards as I don't use C# :p

//==GooS
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
It's okay, besides, I learned C# from C++. I'm taking C++ courses, and self-learning C# at the moment.
 

Vestras

Retired
Reaction score
249
> 1. What math function? What is that stuff? I admit I never knew that stuff existed...

Math is a class in the System namespace. So, it would be:
Code:
Sytstem.Math.Round(...);

> 3. The CreatingEnvironment() method was just the beginning. The program will improve later on, so the name is just a placeholder. What should I name it then?

The "the name is just a placeholder" is bad practice. Really, if you develop bigger programs/libraries, you forget about this and your users will be totally lost. Always name your members correctly the first time.

> 1. Does the int part in the beginning really is part of the C# Standard?? Does C# Standards go with C++ Standards?

No, C# standards definitely don't go with C++ standards. C++ is a much more "compact" language, while C# should be more "readable" and "spacy". (C++ can be readable too though)

I just generally don't do the ", nextVar" thing because I find it to be better to indicate that the variables should be of that type by actually write it more than one time, if you understand.

> 3. As for the variable names, I couldn't think of something that's descriptive. My vocabulary isn't good.

Get creative ;)

> 4. If...else: If I were to write just one statement in an if...else method, I don't need to use parentheses? in the Leaning C# book by O'Reilly, it said that even if there's just one statement, I must use parentheses to make it more readable...Is there something the book didn't say about it?

F*ck O'Reilly, { } for single statements is lame. IMO it makes the statements less readable. That O'Reilly guy probably didn't mention it because he doesn't like it.

This is why I always buy books that has been approved by msdn :thdown:

> Don't think he wanted you to write int on both, though it is more descriptive if you do, but more that he wanted you to initialize the variables (= 0), un-initialized ints, atleast i C++, get "random" values.

Nah, uninitialized variables always get the value null. Anything else would be lame :nuts:

And yeah, I wanted him to write int, because it definitely is more descriptive, as I said above :) Initializing variables (= 0, = null) is just good practice and makes everything more readable, IMO.

> It's okay, besides, I learned C# from C++. I'm taking C++ courses, and self-learning C# at the moment.

Fact: C# has almost no ressemblances to C++, it's very much more like Java, with more strengths.
 

Romek

Super Moderator
Reaction score
964
Variables names should very briefly sum up what the variable contains.

> No wai:
I think declaring multiple variables of the same type on a single line (or not doing so) is personal preference, not some sort of coding convention.

> F*ck O'Reilly, { } for single statements is lame. IMO it makes the statements less readable. That O'Reilly guy probably didn't mention it because he doesn't like it.
F*ck Vestras, no { } for single statements is lame. IMO, it makes the statements less readable. That Vestras guy probably didn't mention it because he doesn't like it.

Basically, I think that's personal preference too, not some convention. It's certainly not a reason to swear at someone over. I'm certain that O'Reilly guy knows what he's doing (more so than you). :p
 

Vestras

Retired
Reaction score
249
Variables names should very briefly sum up what the variable contains.

> No wai:
I think declaring multiple variables of the same type on a single line (or not doing so) is personal preference, not some sort of coding convention.

> F*ck O'Reilly, { } for single statements is lame. IMO it makes the statements less readable. That O'Reilly guy probably didn't mention it because he doesn't like it.
F*ck Vestras, no { } for single statements is lame. IMO, it makes the statements less readable. That Vestras guy probably didn't mention it because he doesn't like it.

Basically, I think that's personal preference too, not some convention. It's certainly not a reason to swear at someone over. I'm certain that O'Reilly guy knows what he's doing (more so than you). :p

I said in my very first post that everything I said was my own opinion. I guess I just swear too often, didn't mean anything bad about it.
 

Xienoph

You can change this now in User CP.
Reaction score
43
2. I don't know how to name those variables. I just threw them all in from my head.
Yeah, it takes practice to come up with a good name.

3. The CreatingEnvironment() method was just the beginning. The program will improve later on, so the name is just a placeholder. What should I name it then?
Hmm ... maybe "round"?

4. Capitalized words means "public accessor"? What is that stuff? I really didn't learn that.
They are basically getters and setters with a lot of syntactic sugar. Instance variables are usually declared as private / protected. To allow access outside the class, you use a method that returns that variable's value (getter) and method that sets that variable's value. More info

2. I thought variables use Pascal notations...
Yah ... it depends from language to language, and from team to team. But generally, local variables use lower case. Class instance variables ... depends. Some people like using "_" at the start, some like adding a type name at the start.
 

KillerChi

New Member
Reaction score
20
Well, I never had any C# courses in college, so I was just messing around, not knowing what to do. I never knew there's so many stuffs I got to learn...:( Guess I better learn from scratch.

It took me about a year to learn tom. Have patience.
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
Improved C#: Rounding

PHP:
using System;

namespace Practice 
{
    public class Lesson_1 //Rounding a number to some places.
    {
        public void IntegerRounding() 
        {
            int number, digit_place;
            float answer;
            
            Console.Write("Enter a value needed to be rounded: ");
            number = Int32.Parse(Console.ReadLine());

            retry:

            Console.Write("Round to what places? [tens: 10, hundreds: 100, etc.]: ");
            digit_place = Int32.Parse(Console.ReadLine());
           
            if (digit_place % 10 != 0 && digit_place % 10 != 1)
            {
                Console.WriteLine("Error: Only multiples of 10 are allowed.");
                goto retry;
            }

            answer = Arithmetics(number, digit_place);
            Console.WriteLine("{0}", answer);
        }

        private float Arithmetics(int number, int digit_place)
        {
            int Condition = number % digit_place;
            if (digit_place != 1)
            {
                if (Condition >= Convert.ToInt32(digit_place * 0.5))
                {
                    number = (number + digit_place) - Condition;
                }
                else
                {
                    number = number - Condition;
                }
                return (float)number;
            }
            else 
            {
                return (float)number;
            }
        }

        public void DecimalRounding()
        {
            float the_number, the_rounding_place;
            
            Console.Write("Enter the decimal value: ");
            the_number = float.Parse(Console.ReadLine());

            retry:

            Console.WriteLine("Round to what place? [0.1: tenths, 0.01: hundredths, etc.]: ");
            the_rounding_place = float.Parse(Console.ReadLine());

            //TODO: Need to know how to check if it's multiple of tens, even if it's less than 1.
            Console.WriteLine("I'm sorry. Currently, it's not implemented yet.");
        }
    }

    class MainComponents 
    {
        public void Run() 
        {
            sbyte choice;
            Lesson_1 StartingPoint = new Lesson_1();

            Console.Write("Choose which number are you rounding with:\n1. Whole Numbers\n2. Decimal Numbers\nYour Choice: ");
            choice = sbyte.Parse(Console.ReadLine());
            switch (choice) 
            {
                case 1: StartingPoint.IntegerRounding();
                    break;
                case 2: StartingPoint.DecimalRounding();
                    break;
            }                     
        }

        static void Main() 
        {
            MainComponents Initializer = new MainComponents();
            Initializer.Run();
        }
    }
}

Thank you for letting me know and for the answers. :)

Okay, I have done some changes, according to feedback. I also added decimal rounding, which is a bottleneck of some sort. I'm still looking up how to round float numbers without using System.Math.Round().

It's just something I wanted to tackle with. Again, I would like feedbacks. Any kind is accepted, even swearing. :)
 

Vestras

Retired
Reaction score
249
> They are basically getters and setters with a lot of syntactic sugar. Instance variables are usually declared as private / protected. To allow access outside the class, you use a method that returns that variable's value (getter) and method that sets that variable's value. More info

Also known as properties ;)

> without using System.Math.Round().

That's lame. Why reinvent the wheel? You already have a method provided, yet you want to rewrite it?

Code:
            digit_place = Int32.Parse(Console.ReadLine());

           
            if (digit_place % 10 != 0 && digit_place % 10 != 1)
            {
                Console.WriteLine("Error: Only multiples of 10 are allowed.");
                goto retry;
            }
        


            answer = Arithmetics(number, digit_place);

Wut? What's up with all those spaces :p This wasn't what I meant with whitespace lines, just one empty line is enough :)

Code:
int number, digit_place;

I generally don't use underscore in my variable names, just do "digitPlace;" instead (IMO)
Also, spread among multiple lines ;)



Code:
public class Lesson_1 //Rounding a number to some places.

Just a little tip, if you want to documentate, use XML comments:

Code:
/// <summary>
/// Rounding a number to some places.
/// </summary>
public class Lesson_1

Code:
int Condition = number % digit_place;

"Condition" ... :eek:

Code:
//TODO: Need to know how to check if it's multiple of tens, even if it's less than 1.

OMG, YES YES YES. I love you dude, this is awesome. Good that you place todo's, it's a good practice :) (Truly)

Code:
sbyte choice;

Just use an int ;) no reason for a signed byte.

Also, very nice that you use switch-case. Much more readable when using more conditions. However:

Code:
                case 1: StartingPoint.IntegerRounding();
                    break;
                case 2: StartingPoint.DecimalRounding();
                    break;

-->

Code:
                case 1:
                    StartingPoint.IntegerRounding();
                    break;
                case 2:
                    StartingPoint.DecimalRounding();
                    break;

:rolleyes:
 

GooS

Azrael
Reaction score
154
Nah, uninitialized variables always get the value null. Anything else would be lame

Did you mean that for C# or that I was wrong about C++?, because:

Code:
int main(int argv, char * args[])
{
	int i;
	cout << i << endl;
	return 0;
}

Returned

2147348480
2147336192
2147344384

For me in three diffrent runs of the program.

//==GooS
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
Hm...it's getting more complicated, I'll point them all out:

1. Why should I reinvent the wheel? This is to learn something without relying on others' help. Learning from scratch gives you more expereinces than learning with a little aid, but I could tell...there's more risk to being stuck in development hell.

2. The spaces were just accidentally added. I was going to use [noparse]
Code:
[/noparse] tags, guess I didn't remove them completely. Will edit it soon.

3. About the variable names, while I was typing them, I couldn't believe myself I could read them wrong. The fact is, with your naming approach, I tend to read slower (about 0.1 seconds slower). I thought, hm...why not make it more readable and more efficiently? So, I decided to add underlines to it. It's faster to read that way, and you won't have to confuse I with l. What do you think about that one?

4. Spreading along multiple lines isn't a good idea, if you were working with pep/7, you could tell why easily. When declaring integers along multiple lines, the debugger has to jump back and forth twice to create memory spaces for those two identifiers, even though they are just one byte apart from each other. I ran the debugger many times, and notice if I write them on one line, the debugger saves time. With two lines, the debugger is a bit slower. Don't professional programmers try to save valuable time? :confused:

I'll stick to one line. I hope you agree with this reason. :)

5. I truly threw everything in there. "Condition", at least it ain't "Chicken" :D.

6. The practice of using TODOs in a code is taught in the Learning C# book I mentioned before. According to it, it's recommended that it be used as a note-taking approach in programming. Not only it's useful, but also it lets other programmers to see what needs to be done.

7. sbyte is just a temporary test subject. I like to try out some new things. :)

8. The switch and newline suggestion: I think that's cool to try it out. Thanks.

9. In C++, values are not nullified. The computer gives the variable integer "i" the actual size of int. It's close to reading it as "zero". Just a hunch.
 

Vestras

Retired
Reaction score
249
3. well, I just generally don't use underscores, do what you want ;)

4. then you must use a really, really bad compiler dude :eek: Anyways, it doesn't really matter much I guess.

7. why use something inappropriate when you can just use an integer ? :confused:

GooS:

I meant for C#, though I didn't know that about C++ :nuts:
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
7. Isn't sbyte legal to be used like that? Since an integer uses up to 32 bits, sbyte uses up 8 bits, and there are very few switch-case conditions, why not use a smaller based type instead?
 

Vestras

Retired
Reaction score
249
7. Isn't sbyte legal to be used like that? Since an integer uses up to 32 bits, sbyte uses up 8 bits, and there are very few switch-case conditions, why not use a smaller based type instead?

Well yes, it is legal. And there's really no reason not to - I'm just used to using int ;)
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,706
Last thing I wanted to say: I can't find a way to round float numbers to some place.

Almost everyone wanted to rely on Math.Round()...Searching around can't give me any acceptable results. If you know how to do it, please post below. Thanks for all of your help. :)
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Monovertex Monovertex:
    How are you all? :D
    +1
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top