How to change the sign to a decimal number in C# - c#

I need a console app that changes the sign to a certain typed number. You type 10, it gives you -10. And so on. I've managed to do that, but I can't do it if I type 1.5 for example. Or any decimal number.
I get "Input string was not in a correct format".
this is what I did.
string inputData = Console.ReadLine();
int a = Convert.ToInt32 (inputData);
int b = a * (-1);
Console.WriteLine(b);
Console.ReadLine();

You need to use decimal as a variable type if you want to work with decimal numbers
If so, use Convert.ToDecimal instead of ToInt32
You don't really need to use multiplication here, it's enough just to use -a instead
string inputData = Console.ReadLine();
decimal a = Convert.ToDecimal (inputData);
decimal b = -a;
Console.WriteLine(b);
Console.ReadLine();

Related

3 equals 51 in C# [duplicate]

I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.
double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.
I think there are some compiler errors.
Writeline should be WriteLine (capital 'L')
missing semicolon at the end of a line
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
a = double.Parse(Console.ReadLine());
b = a * Math.PI; // Missing colon!
Console.WriteLine("Sonuç " + b);
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine() reads a string (so then you need to change the string to a double)
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
double a,b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
try
{
a = Convert.ToDouble(Console.ReadLine());
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
}
catch (Exception)
{
Console.WriteLine("dönüştürme hatası");
throw;
}
Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.
int userInput = int.parse(Console.ReadLine());
here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.
You're missing a semicolon: double b = a * Math.PI;

Get string from large double value(C#)

Can't find simple way to convert double to string. I need to convert large numbers without distortion. Such as:
double d = 11111111111111111111;
string s = d.ToString();
Console.WriteLine(s);
//1.11111111111111E+19
How to get string value from double value exactly the same as user enter.
11111111111111111111111 => "11111111111111111111111"
1.111111111111111111111 => "1.111111111111111111111"
Any ideas how it can be done?
double is a floating point type. So it has a limited accuracy. In your example, you could do something like this:
double d = 11111111111111111111;
string s = d.ToString("F0");
Console.WriteLine(s);
But as you'll see,this would output 11111111111111100000 instead of 11111111111111111111,so it has lost accuracy in the process. So the answer here is use the right type for the work. If you need a string, use a string variable to store the value.
Edit
This was the question i was trying to find that explains the problem with floating point math., thanks to #GSerg
First of all: 11111111111111111111111 is to large for a double value and also this value: 1.111111111111111111111 since the double max decimal length is 17.
By default, a Double value contains 15 decimal digits of precision,
although a maximum of 17 digits is maintained internally.
For this reason you should use BigInteger and then ToString for formatting the output.
There is also a library in the nuget Directory called BigRational, never used and seems in Beta stage but probably will help in solving this problem.
In general case, you can't do this: user can well input, say 123, in many a way:
123
123.00
1.23e2
12.3E1
123.0e+00
1230e-1
etc. When you convert the user input into double you loose the initial format:
string userInput = ...
// double is just 123.0 whatever input has been
double value = double.Parse(userInput);
In case you want to drop exponent if it's possible you can
double value = 11111111111111111111;
string result = value.ToString("#######################");
And, please, notice, that double has 64 bit to store the value, that's why a distortion is inevitable for large numbers:
// possible double, which will be rounded up
double big = 123456789123456789123456789.0;
// 1.2345678912345679E+26
Console.WriteLine(big.ToString("R"));
// 123456789123457000000000000
Console.WriteLine(big.ToString("###########################"));
May be you want BigInteger instead of double:
using System.Numerics;
...
BigInteger value = BigInteger.Parse("111111111111111111111111111111111");
// 111111111111111111111111111111111
Console.WriteLine(value.ToString());

Simple binary to decimal converter - Issue in C#

I've made a simple binary to decimal converter, used to work fine, I used a string variable to declare the values, but now realise I will need to store them as integers as I wanted to add in a while loop structure to validate the users choice so they could only enter 0 or 1's.
But I now have a program which says Cannot convert from 'int' to 'System.IFormatProvider'.. As I am a beginner with C#,
I have no idea what this means, and how to over come the problem, any help appreciated.. Here is my code if anyone wants to look at it:
int iBinaryNum; //To store binary number
int iDecimalNum; //To store decimal numbers
//Validation of user choice & main program
while (iBinaryNum == 0 || iBinaryNum == 1)
{
Console.WriteLine("Enter the binary number you want to convert to decimal");
iBinaryNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Binary number you have entered is " + iBinaryNum);
iDecimalNum = Convert.ToInt32(iBinaryNum, 2);
Console.WriteLine("This converted into decimal is " + iDecimalNum);
}
//If it's not equal to 0 or 1
Console.WriteLine("Invalid binary number, Please re-enter");
//Prevent program from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
iDecimalNum = Convert.ToInt32(iBinaryNum, 2);
The arguments you passed are int, int. As you can see here, you can either choose between Object, IFormatProvider, String, IFormatProvider or String, Int32.
Since the first int can only be used as Object, this means the second argument has to be IFormatProvider.
If you want a solution, you'll have to clarify what it is you're trying to do. Why do you want to convert an integer to an integer?
Convert.ToInt32(String, Int32) requires the first argument to be a String and the second an integer. You are passing two ints, which resolves to Convert.ToInt32(Object, IFormatProvider) which generates the error. You have to convert the first argument (iBinaryNum) to a String.
But I don't think your code works as you expect, since the while condition only checks if either of the ints is either 1 or 0. If the user enters 1110 it fails. Also, if the user enters anything above Int32.Max (which wouldn't be too surprising, considering how large binary numbers can grow), your program crashes. I would store the user input in a string again and check each character whether it contains valid characters (1 or 0).
Like this:
bool IsBinaryNumber(string test){
foreach(char c in test){
// If c is not either 0 or 1, break.
if(!((c=='0') || (c== '1'))){
return false;
}
}
// If everything went well, it's a binary number.
return true;
}
Complete Solution:
You can Use Regular Expressions to Check for Particular pattern in the Input String
The following program will take the Binary input from user and converts it into the decimal till the invalid value is found
string strBinaryNum=""; //To store binary number
int iDecimalNum; //To store decimal numbers
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[0-1]+$");
Console.WriteLine("Enter the binary number you want to convert to decimal");
strBinaryNum = Console.ReadLine();
while(r.Match(strBinaryNum).Success)
{
Console.WriteLine("The Binary number you have entered is " + strBinaryNum);
iDecimalNum = Convert.ToInt32(strBinaryNum, 2);
Console.WriteLine("This converted into decimal is " + iDecimalNum);
Console.WriteLine("Enter the binary number you want to convert to decimal");
strBinaryNum = Console.ReadLine();
}
Console.WriteLine("Press any key to close");
Console.ReadKey();
If you look at the different overload of Convert.ToInt32, you will see there are none that take as parameters Int32, Int32.
The overload resolution will select the one that takes object, IFormatProvider instead and 2 is an Int32, not a type that implements IFormatProvider, hence the error.
It is not clear why you are trying to convert an Int32 into an Int32 - you already have the value in iBinaryNum.
I'm not sure I really understand the problem. However here is a loop that will keep the only continue once the binary number requirements have been met.
uint iBinaryNum = 2; //To store binary number
decimal iDecimalNum; //To store decimal numbers
//Validation of user choice & main program
while (iBinaryNum > 1)
{
Console.Write("Enter the binary number you want to convert to decimal: ");
if (!uint.TryParse(Console.ReadLine(), out iBinaryNum) || iBinaryNum > 1)
{
//If it's not equal to 0 or 1
Console.WriteLine("Invalid binary number, Please re-enter");
iBinaryNum = 2;
}
}
iDecimalNum = Convert.ToDecimal(iBinaryNum);
Console.WriteLine("This converted into decimal is " + iDecimalNum);

Printing double values

On my system, the following code prints '3.6':
double a = 1.2;
int b = 3;
double c = a * b;
Console.WriteLine(c);
But in the debugger, I can see that c has a value with more than 2 digits:
I know that I can display the full representation with Console.WriteLine("{0:R}", c). Is this the only and recommended way to display the actual value of a double?
update
Going with the above example, I'd like to print c such that if the user were to take the printed value and insert that back into the code in a test using ==, the comparison would be true. In this case c == 3.5999999999999996 returns true.
Console.WriteLine calls Double.ToString which uses the the "G" format specifier. This uses the current culture to determine the number of decimal places (1 for "en-US").
If you want to display 8 decimal places you can use the numeric format specifier:
Console.WriteLine(c.ToString("N8"));
Standard Numeric Format Strings
Edit: The debugger uses this method to convert a double to a string:
_ecvt_s
I assume it's the cheapest way to convert it.
Where i have found it: How does Visual Studio display a System.Double during debugging?
3.999999999999996 is not the actual value of the double either; that's just the value rounded off to fifteen places or whatever. There is no built-in way to display the actual exact value that the double is representing. This is really too bad, because every normal double can be represented exactly as a decimal string, and it would be nice to be able to see that.
As a public service, I've put source code for a device which does that on my blog:
http://ericlippert.com/2011/02/17/looking-inside-a-double/
Note that it uses the Rational class from Microsoft Solver Foundation. If you don't have that then you can either download it for free, or write your own Rational class; it's character-building to do so.
If the subject of how doubles work internally interests you, consider checking out my archive of handy articles explaining all that. It's at:
http://blogs.msdn.com/b/ericlippert/archive/tags/floating+point+arithmetic/
Start from the bottom; those are in reverse-chronological order.
You could also use a different approach for example if you want to return 2 decimal places you could try something like this
double a = 1.2;
int b = 3;
double c = a * b;
var s = string.Format("{0:0.00}", c);
Console.WriteLine(s);
Output = 3.60
if you want to suppress the last 0 where out put is 3.6 you could do
var s = string.Format("{0:0.##}", c);
Output = 3.6 feel free to play around with it
double a = 1.2;
int b = 3;
double c = a * b;
string formatted = c.ToString("N5");
Console.WriteLine(formatted);

How to take away fraction part from decimal?

How to take away fraction part while formatting decimal type in .NET? I need common syntax for both variants. Is there any gentle solution?
decimal a = 1.22M;
decimal b = 1.00M;
String.Format("${0}", a); // result is $1.22
String.Format("${0}", b); // result is $1.00, should be $1, HOW?
Assuming that 'common syntax' means that you need one solution to give both outputs, String.Format("${0:#.##}", x) does the trick. When x is 1.00M, the result will be "$1". when x is 1.22M, the result is "$1.22".
Try these - both will output the appropriate currency symbol for the current system:
a.ToString("C2"); // Outputs 2DP
b.ToString("C0"); // Outputs no DP
If you need to supply a specific currency symbol, use the same as above, but substitute N for C.
The Decimal type is designed to keep track of how many significant digits it has. That is why 1.00M.ToString() returns the string 1.00.
To print a Decimal without the factional part you can use the format specifier N with precision 0:
1.22M.ToString("N0") => "1"
1.00M.ToString("N0") => "1"
1.77M.ToString("N0") => "2"
This will round the Decimal in the conversion process.
In VB.NET I would use
CINT(INT(a))
I imagine a C# variant exists.
I found a probable solution at this link:
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
To further explain:
decimal a = 1.55M;
Console.WriteLine("$" & CInt(Int(a)).ToString()); // result is $2
decimal b = 1.22M;
Console.WriteLine("$" & CInt(Int(b)).ToString()); // result is $1
I would steer away from utilizing the currency format as the decimals are inherent to that class.
string.Format("${0:0}",b)
In C# you can use {0} to tell a parameter, and {0:format} to tell a parameter with format.
EDIT
Oh I thought what OP want to do is removing the digits of b. But now I realized that he wants to remove useless zeroes.
string.Format("${0:#.##}",b)
There are other issues here I think. If the question is to completely ignore decimal places, then just casting to an integer would produce the required output, but would obviously loose precision, which is not a good thing.
There are also rounding considerations when formatting as a string like example below.
decimal a = 1.55M;
Console.WriteLine(a.ToString("C0")); // result is $2
decimal b = 1.22M;
Console.WriteLine( b.ToString( "C0" ) ); // result is $1
I presume that this is just for dispaly and not for changing data type to INT when number has no value after decimal.
using System;
namespace stackOverflow
{
class Program
{
static void Main(string[] args)
{
decimal a = 1.2245M;
decimal b = 1.00M;
Console.WriteLine("Your percentage to date is: {0:#.#####}", a);
Console.WriteLine("Your percentage to date is: {0:#.#####}", b);//#.#### gives number upto 4 decimal
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double n, x;
int a, dec = 0;
Console.WriteLine("Enter double");
n = Convert.ToDouble(Console.ReadLine());
a = Convert.ToInt32(n);
x = n - a;
if (x < 0)
a--;
int k = 1000;
for (int i = 0; i < n.ToString().Length; i++)
{
if (n.ToString()[i] == '.')
k = i;
if (i > k)
dec = dec * 10 + (n.ToString()[i]-48);
}
Console.WriteLine("Non-fraction " + a);
Console.WriteLine("Fraction " + dec);
Console.ReadKey();
}
}
}

Categories

Resources