Output numeric formatting is wrong - c#

I'm writing a program in C# that turns the number (given by an user) to a decimal number with the $ mark. For example, if i give in 15 then the results should be $15.00 but the results now is 15.00 ?.
I have tried to put en-US behind it but it doesn't work
Console.Write("Give a number that you want to convert to $: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("Money: {0}", number.ToString("C"));
Edit:
My teacher doesn't allow it to just put "$" in front of it.

This should work regardless of your machine's culture info:
Console.WriteLine("Money: {0}",
number.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")));

Related

displaying decimal values depending on decimal places in string.format

I'm using String.Format for displaying validation messages. I'm trying to achieve a scenario where, if decimal is there, show 12.34, else don't show any decimal points like, 12.
I tried to achieve it by using type as number. My string is,
Please enter value between {1:N} and {2:N}. // Displays 1.00 and 2.00
Please enter value between {1:N0} and {2:N0}. // Displays 1 and 2
What I should do to fix this? I need comma separation depending on culture. Using {1:G} will not provide that.
Try using :G . for isntance: Please enter value between {1:G} and {2:G}. Or {1:0.##}
The 0 means a digit will always be shown. Use a # to show optional digits.
{1:0.##}

Formatting Output in C# With Curly Brackets

What do the values within the curly brackets do in this example?
{
double price = 1234.56
Console.WriteLine("TV{0:F0} is {1:C}" , 2, price);
Console.Read();
}
Basically the first number ist the index of the argument (0 means 2, 1 means price in your example).
The value after the colon is one of the Standard Numeric Format Strings, see MSDN-Docs for available options.
{0:F0} prints 2 because parameter 0 is 2 and format is Fixed Point with zero decimal places (F0)
{1:C} prints $1234,56becaus parameter 1 (price) is 1234.56 and format is Currency (C)
This example uses only Format Strings for numerics, there are also Standard Format Strings for DateTime and so on..
What do the values within the curly brackets do in this example?
They are format specifications for the values provided. Essentially, it instructs the Console.WriteLine function how to format the values as strings for output to the console. Here is a .NET fiddle that exemplifies this.
The MSDN documentation has an extensive example that shows how these work.
{0:F0} takes the given 2 int value, and simply prints it as 2, "2"
{1:C} takes the given 1234.56 double value and treats it as currency, "$1,234.45".
The 0 and 1 are significant as they are the zero-based array indicator of the location in which the parameters map to the string formatting. For example, the below demonstrates outputs from altering the arguments to better visualize the impact.
Console.WriteLine("TV{0:F0} is {1:C}", 2, price); // Prints TV2 is $1,234.56
Console.WriteLine("TV{0:F0} is {1:C}", price, 2); // Prints TV1234 is $2.00

How do I parse an integer, using the rule that +5 is not valid but 5 is?

My program asks the user to input a number from 1 - 10 in a text box in. When I the user inputs the number I have it converted into an int, by using this:
if (!int.TryParse(inputBox.Text, out input))
I used the ! because if the number cannot be TryParse'd into a int it throws an error to the user.
This works, until I enter a number that begins with a +, for example +5, or +1. It isn't catching the fact that there is a + in front of the int. If I enter more than one + it throws an error like it should.
How would someone make an error proofing line(s) of code that checks for this type of input?
I think you want to allow 1-10 without the positive sign (+).
int number;
var input = numberTextBox.Text;
if (!input.StartsWith("+") && int.TryParse(input, out number))
{
//valid input, check if it's between 1-10
}
But I think the requirement is really strange. "+10" is considered the same as "10", it is a valid input.
There is an overload of Int32.TryParse that accepts a NumberStyles value and an IFormatProvider. - https://msdn.microsoft.com/en-us/library/zf50za27(v=vs.110).aspx
The default used by Int32.TryParse is NumberStyles.Integer, which allows leading and trailing whitespace, and leading signs.
int.TryParse("+5", NumberStyles.None, NumberFormatInfo.InvariantInfo, out x), for example, returns false - however, it also returns false for -5, since the option to include a leading sign doesn't differentiate between a + and -. This is a hint that you probably shouldn't either, "+5" is every bit an integer as "5" and "-5".
You can remove + from textBox at runtime or check + character as shown in below code
if (inputBox.Text.Contains("+"))
{
// throw or show message
return;
}
if (!int.TryParse(inputBox.Text, out input))
{
}
If you want to show popup while press, you can check above condition in textbox TextChangeEvent,
Or use keypress event to restrict input.

How come C# integer input doesn't accept the correct value?

I've recently started to code in C#, so I'm just learning the basics right now. I've tried to search for this through Google and on this site, however, I couldn't find any solutions, but basically when I do Console.Read(), and take in an input and store it into an integer variable, the value I input is strangely different when it is outputted.
Here is the block of code I am trying to run:
Console.WriteLine("Welcome To The Program!");
Console.Write("Enter the radius of the sun: ");
input = Console.Read();
Console.WriteLine(input);
Console.ReadKey();
Input is a type of int and when I type in say 5, it will output 53. If I input 0, it will output 48.
Can anyone please explain why this may be happening? I know there is a way to parse input by first taking it as a string input and then parsing it as an integer, but that would take too long for larger pieces of code.
Put it inside Convert.ToInt32 since you are reading the line as string value like this:
input = Convert.ToInt32(Console.Read());
For the record, the reason this didn't work is because Console.Read returns the ASCII integer representation of the first character entered in the console. The reason that "5" echoed 53 to the screen is this:
Console.Read begins reading from the console's In stream.
The first character in the stream is '5'.
The ASCII value of '5' is 53.
"input" is assigned the value of 53.
This should solve your problem:
input = int.Parse(Console.ReadLine());
You can also better use this:
int number;
if(!int.TryParse(Console.ReadLine(), out number)){
Console.WriteLine("Input was not an integer.");
return;
}
Console.WriteLine(number);
You are receiving the ASCII value of the character in question. In order to get what you want, you have to accept a string and then parse it. It will take less time than you think.
If you only want to read one character at a time, then you can use the following:
int input = int.Parse(((char)Console.Read()).ToString());
This gets the character of the code point and then turns it into a string before it is parsed. However, if you are going to have more than one character or there is any chance that the input won't be a number, then you should look at HeshamERAQI's response.

Formatting Math.Pow Output

I hate to ask such a dumb question, but I'm just starting out, so here goes.
myString = "2 to 2.5 power is " + Math.Pow(2, 2.5);
I want to format the resulting number to 4 decimal places and show the string in a MessageBox. I can't seem to figure this out or find the answer in the book. Thanks!
The ToString method should do the trick. You might need to look it up in the MSDN to find more formatting options.
Math.Pow(2, 2.5).ToString("N4")
To show a string in a MessageBox you use MessageBox.Show. In particular, there is an overload accepting a single string parameter that will be displayed in the MessageBox. Thus, we need
string s = // our formatted string
MessageBox.Show(s);
Now, let's figure out what our string is. A useful method here is String.Format. A useful reference here is the Standard Numeric Format Strings page on MSDN. In particular, I draw your attention to the fixed-point specifier "F" or "f":
The fixed-point ("F) format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative.
The precision specifier indicates the desired number of decimal places.
Thus, we want
double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);
so, putting it all together,
double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);
MessageBox.Show(s);
string.format("2 to 2.5 power is {0:0.000}", Math.Pow(2, 2.5));
Math.Pow(2, 2.5).ToString("N4")
is what you want I think.
more formatting options
It's not a dumb question: several of the other answers are wrong.
MessageBox.Show(string.Format("2 to 2.5 power is {0:F4}", Math.Pow(2, 2.5)));

Categories