[C# Solution] Rounding

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
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
248
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,667
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,667
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
248
> 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
963
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
248
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,667
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
248
> 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,667
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
248
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,667
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
248
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,667
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.
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top