c# ToString a decimal and force + sign AND number decimal places - c#

How can I do two things in tostring format:
1. Display number to x decimal places
2. Also force a + sign so that negative an positive numbers lineup in nice columns.
string fmt = "+N" + dp + ";-N" + dp;
Console.WrtieLine(Open.ToString(fmt))
Does not work?

You'll need to create a custom format string to do what you want. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx tells you about these but the below is a quick example of one thing that does the trick.
double num = 1111.019123;
int dp = 2;
string format = String.Format("+#.{0};-#.{0}",new string ('#',dp));
Console.WriteLine(num.ToString(format));

Related

How to compare currency or alphanumeric values in C#

The value that extracted from the application is in string format for ex. "$0.38". So, I segregated each character in the given string using IsDigit then appended them together using string builder. The digit can also be alphanumeric like "12,365.23 AS". Is there a way to recover only numeric part (along with the decimal) from the given string.
But Output I receive is "38" instead of "0.38". I also want to compare that the given string value lies between the upperLimit and lowerLimit provided.
Please let me know how to proceed with the same.
string Value = "$0.38";
int upperLimit = 2500;
int lowerLimit = 50000;
StringBuilder sb = new StringBuilder();
//sb.Append(someString);
foreach (char amin in Value)
{
if (System.Char.IsDigit(amin))
{
sb.Append(amin);
}
}
int compareVal = Convert.ToInt32(sb.ToString());
Console.WriteLine("value for comparision" + " " + compareVal);
The best way is using one of the overloads of decimal.Parse:
string Value = "$0.38";
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
decimal dd=decimal.Parse(Value, System.Globalization.NumberStyles.AllowCurrencySymbol|System.Globalization.NumberStyles.AllowDecimalPoint,culture);
Note the use of NumberStyles enum.That way you can control exaclty the parsing.
There are two reasons why you will get 38:
StringBuilder looks like "038", since "." is not a digit (just like "$").
Convert.ToInt32(...) returns an integer which doesn't allow decimal digits.
The better data type for currencies is decimal, a high precision floating point data type so to say.
Try
var amount = decimal.Parse(Value , NumberStyles.Currency)
var isInLimit = upperLimit <= amount && amount <= lowerLimit; // i guess you swapped upper and lower limit btw. ;)
instead.
Edit
In order to use the NumberStyles-Enumeration, you will have to use tha correct namespace in your file:
using System.Globalization;
You are omitting the decimal point and you are not using a decimal data type to hold the converted value. The real way to go is to convert the currency string to a decimal number:
CultureInfo usCulture = new CultureInfo("en-US)";
decimal amount = decimal.Parse(Value, NumberStyles.Currency, usCulture);
You can then perform a proper numeric comparison:
if (amount <= upperLimit && amount >= lowerLimit)
....
I first marked the question as a duplicate, but then changed my mind. I still think it is very much related to: Convert any currency string to double

How to always show 3 numbers after decimal point C#

I am currently displaying a number that is being rounded to 3 decimal places e.g. 0.31, using Math.Pow, the only problem is I want to display this number to say 0.310 (for styling purposes) does anyone know if this is possible?
The Fixed-Point Format Specifier can be used in a call to ToString or in string.Format:
double x = 1493.1987;
string s1 = x.ToString("F3");
string s2 = string.Format("Your total is {0:F3}, have a nice day.", x);
// s1 is "1493.199"
// s2 is "Your total is 1493.199, have a nice day."
Note that the Fixed-Point Format Specifier will always show the number of decimal digits you specify. For example:
double y = 1493;
string s3 = y.ToString("F3");
// s3 is "1493.000"
Use the format in the toString
double pi = 3.1415927;
string output = pi.ToString("#.000");
Here is an updated example that also works w/o having to call .ToString():
float a = 12.3578f;
double b = 12.3578d;
Console.WriteLine("The tolerance specs are: {0:F4} and: {1:F3}", a,b);
ANSWER: The tolerance specs are: 12.3578 and: 12.358

Number increment from string value

I my application due to some reason I have two numbers in 5 digits.
The following code give you brief idea.
string s = "00001"; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + s;
//Operation end
//Increment the value of s by 1. i.e 00001 to 00002
This can be done easily by convert the value of s to int and increment it by 1 but after all that I have to also store the incremented value of s in 5 digit so it will be "00002".
This think give me a pain...
use
string s = "00001";
int number = Convert.ToInt32(s);
number += 1;
string str = number.ToString("D5");
to get atleast 5 digits.
The "D" (or decimal) format specifier
If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no
precision specifier is specified, the default is the minimum value
required to represent the integer without leading zeros.
This seems to work for me.
string s = "00001";
int i = Int32.Parse(s);
i++;
s = i.ToString("D" + s.Length);
So I think you want to know how to convert an int to a 5 digit string.
You can do this:
int i = 1;
string s = i.ToString("D5");
//s = "00001"
There are plenty of format examples here.
Use String.Format() to achieve this:
string str = String.Format({0:#####}, s);
Look here.
This works using the PadLeft function:
int i = 1; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + i.ToString().PadLeft(5, '0');
//Operation end

Formatting a string number

I want to format a string number. For example:
double number="118176";
It should look like 1181.71 or 1181,71.
I couldn't find any format type. I tried some of format types as ToString("#,0") but it didn't work.
Thanks for any advice.
First of all: a double variable can not take a string. But that aside, something like this should help:
double number = 1181.76;
string output = String.Format("{0:d2}", number);
This takes the number and creates a string from it using the decimal number format with 2 decimal places.
What you didn't say is why you expect the integer 118176 to magically turn into a double with two decimals? The only way would be
double number = 118176;
string output = String.Format("{0:d2}", number / 100.0);
EDIT
Doing what you describe in your comment is a bit more complex:
string priceString = nodeFareList.SelectSingleNode("GenQuoteDetails/TotAmt").InnerText;
double priceDouble = Convert.ToDouble(priceString) / 100.0;
price.InnerHtml += String.Format("{0:c}", priceDouble);
This converts the number in priceDouble to a string with the value formatted like a currency. If you do not want the currency symbol, use the following:
price.InnerHtml += String.Format("{0:d2}", priceDouble);
See Fixed-point on this page (assuming .net): http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
You'll have to divide by 100 first though.
I think, what you are looking for is this:
String.Format("{0:0,0.0}", 12345.67);
String.Format("{0:0,0}", 12345.67);
See here for details.
Use can refer the below code in case of Java.
1) First define the Decimal Format instance.
DecimalFormat decimalFormat = new DecimalFormat("####.##");
2) Then pass the decimal value to the 'format' method
String dummyString = decimalFormat.format(pressureValue).toString()
where pressureValue - Decimal number
Hope this will be useful.

Float value should have 2 decimals

I am getting the output as 756.4 but this is equal to 756.40 i know that but still i would like to save it as 756.40 so how can i convert that to the required one
Forgot to mention my totalamount is declared as float
Amount[index] //In this amount is declared as arraylist
totalAmount += float.Parse(Amount[index].ToString());
Here after all additons done after the loop i would like to get the required one
A sample code of conversion
if (totalAmount.ToString().Contains("."))
{
string[] b = totalAmount.ToString().Split('.');
Dollars = b[0].ToString().PadLeft(10, (char)48);
cents = b[1].ToString().PadRight(2, (char)48).Substring(0, 2);
}
else
{
Dollars = totalAmount.ToString().PadLeft(10, (char)48);
cents = "00";
}
FormattedTotalAmounts = Dollars + cents; // Here i am getting the output as i said
string totalAmountFormatted = totalAmount.ToString("F2");
This formats the total amount as a fixed-point number (F) with two decimal places (2). For details about these format strings, see the following two MSDN articles:
Standard Numeric Format Strings
Custom Numeric Format Strings
String.Format("{0:0.00}", 756.4);
In your code change this
if (totalAmount.ToString().Contains("."))
{
string[] b = totalAmount.ToString().Split('.');
Dollars = b[0].ToString().PadLeft(10, (char)48);
cents = b[1].ToString().PadRight(2, (char)48).Substring(0, 2);
}
else
{
Dollars = totalAmount.ToString("F2").PadLeft(10, (char)48);//Necessary change
cents = "00";
}
FormattedTotalAmounts = Dollars + cents;
Try this:
decimal t = 756.40m;
MessageBox.Show(t.ToString("0.00"));
you can use numberformat in your ToString like
SomeVar.ToString("#,##0.00")
First, I think you should probably be using Decimal if this is financial data.
Second, numeric values don't have trailing spaces, strings do.
EDIT: C# 2.0 tag added - LINQ removed.
Decimal total;
foreach (object oAmount in Amount)
{
Decimal amount = (Decimal)oAmount;
total += amount;
}
String FormattedTotalAmounts = total.ToString("G");
passing "F" to ToString will work equally well.
EDIT responding to comment.
String FormattedTotalAmounts = total.ToString("0000000000.00");
gives 10 0's on the left and 2 0's on the right.

Categories

Resources