Let's say I have a string
string totalAmount = "100";
string price = "Price";
ALPHA = Price + totalAmount
I know that one line of the docket can have 42 characters.
I want to print this on a docket such that the "Price" is on the left hand side of the docket and the "totalAmount" is on the right hand side.
How would I do this?
PadRight should help you in this case.
string totalAmount = "100";
string price = "Price";
string result = price.PadRight(42 - totalAmount.Length) + totalAmount;
You can use the String.PadLeft / String.PadRight methods of the .net Framework if you use a font like Courier that have the same width for each character.
string totalAmount = "100".
ALPHA = "Price" + totalAmount.PadLeft(37, " ");
You can use String.PadRight and String.PadLeft to achive this.
string totalAmount = "100".PadLeft(37).
ALPHA = "Price" + totalAmount
Related
var rounded = Math.Round(value, 1);
string prob = string.Format("{0:P}", rounded);
Example:
value : 0.599..
rounded: 0.6
prob : 60.00 %
I want the prob to be just 60 % How can I do this?
Use {0:0%} if you want "60%" without a space between the number and percent symbol.
Use {0:P0} if you want "60 %" with a space.
var value = 0.599;
var rounded = Math.Round(value, 1);
string prob1 = string.Format("{0:0%}", rounded);
Console.WriteLine(prob1);
// prints "60%"
string prob2 = string.Format("{0:P0}", rounded);
Console.WriteLine(prob2);
// prints "60 %"
I would like to format some numbers to strings in C# with custom group/thousands separator and decimal separator. The group and decimal separator can change based on user input so I would like to use a NumberFormatInfo object instead of a hardcoded formatting string. My code below gets the proper separators, but it changes the precision of the number to always be two decimal places, whereas I want to keep the full precision of the number and only show decimal places when needed (so integer values dont have decimal places).
How can I achieve this? I am guessing I need to change the "N" parameter, but change it to what?
double n1 = 1234;
double n2 = 1234.5;
double n3 = 1234567.89;
double n4 = 1234.567;
var nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
nfi.NumberGroupSeparator = " ";
string s1 = n1.ToString("N", nfi); //want "1 234" but I get "1 234,00"
string s2 = n2.ToString("N", nfi); //want "1 234,5" but I get "1 234,50"
string s3 = n3.ToString("N", nfi); //correct output of "1 234 567,89"
string s4 = n4.ToString("N", nfi); //want " 1 234,567" but I get "1 234,57"
Below is the solution I came up with as an extension method.
public static string Format(this double d, NumberFormatInfo numberFormatInfo)
{
string s = d.ToString(CultureInfo.InvariantCulture);
int index = s.IndexOf('.');
int decimalPlaces = index == -1 ? 0 : s.Length - index - 1;
return d.ToString($"N{decimalPlaces}", numberFormatInfo);
}
Edit:
There is a workaround using built-in ToString() (by using digit placeholder #) and Replace and/or Trim:
double n1 = 1234;
double n2 = 1234.5;
double n3 = 1234567.89;
double n4 = 1234.567;
string s1 = n1.ToString("### ### ###.###").Replace(".",",").Trim();
string s2 = n2.ToString("### ### ###.###").Replace(".", ",").Trim();
string s3 = n3.ToString("### ### ###.###").Replace(".", ",").Trim();
string s4 = n4.ToString("### ### ###.###").Replace(".", ",").Trim();
Combining it with numeric format to read , as decimal separator doesn't work though:
double n1 = 1234;
double n2 = 1234.5;
double n3 = 1234567.89;
double n4 = 1234.567;
var nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
nfi.NumberGroupSeparator = " ";
string s1 = n1.ToString("### ### ###,###", nfi); //doesn't work
string s2 = n2.ToString("### ### ###,###", nfi);
string s3 = n3.ToString("### ### ###,###", nfi);
string s4 = n4.ToString("### ### ###,###", nfi);
Original:
I guess you cannot use only the built-in ToString() to get it right. You probably need some LINQ tricks to get the result you want:
double n1 = 1234;
double n2 = 1234.5;
double n3 = 1234567.89;
double n4 = 1234.567;
var nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
nfi.NumberGroupSeparator = " ";
string s1 = new string(n1.ToString("N", nfi).Reverse().SkipWhile(x => x == '0' || x == ',').Reverse().ToArray());
string s2 = new string(n2.ToString("N", nfi).Reverse().SkipWhile(x => x == '0' || x == ',').Reverse().ToArray());
string s3 = new string(n3.ToString("N", nfi).Reverse().SkipWhile(x => x == '0' || x == ',').Reverse().ToArray());
string s4 = new string(n4.ToString("N", nfi).Reverse().SkipWhile(x => x == '0' || x == ',').Reverse().ToArray());
There reason is because of the two things as follow:
First, double is not precise. When you input something like double n = 1234.5, the actual double value stored could be something like n = 1234.499999999999998
Second, it is about ToString(). It is really used only for formatting. In other words, depends on how you dictate it, it will show something out. For instance, if you give instruction to show the number with 2 significant digits after decimal separator, then it will show the number with exactly 2 significant digits after decimal separator.
Now, putting the two things together we got a dilemma here! What you want the program to do is: "Show my as many number of significant digits as it needs to be". However, when you input double n = 1234.5, the program will show 1234.499999999999998 instead! But on the other hand, you also do not want to fix the number after decimal separator.
So, I guess you should be using LINQ SkipWhile and Reverse to do that, not by simple built-in.
//this is the best way for you:
s3 = n3.ToString($"### ##0{CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator}00");
//or my prefer:
s3 = n3.ToString($"###{CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator}##0{CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator}00");
//I am always using this. nop. it is best and smallest way. :)
//Best Regards. Ersin Kecis.
You can increase the number of decimal places in NumberFormatInfo and use TrimEnd() to remove additional zeros and seperators.
nfi.NumberDecimalDigits = 15;
public static string FormatDouble(double d, NumberFormatInfo nfi)
{
return d.ToString("N", nfi).TrimEnd('0', ' ', ',', '.');
}
i have this code in my updatetobill code. im planning to round it off to nearest tenth i think? for example the price is 123456.123456, what i want to do is to have it as 123456.12 because since its a price, i need the cents. thanks in advance for any help :)
private void UpdateTotalBill()
{
double vat = 0;
double TotalPrice = 0;
long TotalProducts = 0;
foreach (DataListItem item in dlCartProducts.Items)
{
Label PriceLabel = item.FindControl("lblPrice") as Label; // get price
TextBox ProductQuantity = item.FindControl("txtProductQuantity") as TextBox; // get quantity
double ProductPrice = Convert.ToInt64(PriceLabel.Text) * Convert.ToInt64(ProductQuantity.Text); //computation fro product price. price * quantity
vat = (TotalPrice + ProductPrice) * 0.12; // computation for total price. total price + product price
TotalPrice = TotalPrice + ProductPrice+40 +vat;
TotalProducts = TotalProducts + Convert.ToInt32(ProductQuantity.Text);
}
Label1.Text = Convert.ToString(vat);
txtTotalPrice.Text = Convert.ToString(TotalPrice); // put both total price and product values and converting them to string
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
Just round it Math.Round like;
Math.Round(TotalPrice, 2) // 123456.12
Also you can use Math.Round(Double, Int32, MidpointRounding) overload to specify your MidpointRounding is AwayFromZero or ToEven. ToEven is the default option.
The best way to do this when you want to transform string is using the CurrencyFormat. You can use the code below:
txtTotalPrice.Text = TotalPrice.ToString("C");
txtTotalProducts.Text = TotalProducts.ToString("C");
Instead which:
txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);
I want the program to get all of the elem1-elem7 info, add it together, and put it into the totalElem variable. That part works fine.
The part I'm stuck on, is that I want to take that number (lets say 30 for example), and put it on the end of a decimal to use it as a multiplier. Therefore 30 would become 1.30.
The error I'm getting is:
Cannot implicitly convert type 'string' to 'decimal'.
Please note, that is not where the variable definitions really are in the code. I just put them there so I didn't have to post my whole program.
private void calculateButton_Click(object sender, EventArgs e)
{
int startingSheetDPS;
int chd;
int skill;
int elem7;
int elem6;
int elem5;
int elem4;
int elem3;
int elem2;
int elem1;
int totalElem;
decimal elemMultiplier;
decimal baseMultiplier;
elem1 = Convert.ToInt32(ele1.Text);
elem2 = Convert.ToInt32(ele2.Text);
elem3 = Convert.ToInt32(ele3.Text);
elem4 = Convert.ToInt32(ele4.Text);
elem5 = Convert.ToInt32(ele5.Text);
elem6 = Convert.ToInt32(ele6.Text);
elem7 = Convert.ToInt32(ele7.Text);
chd = Convert.ToInt32(chd1.Text);
skill = Convert.ToInt32(skill1.Text);
totalElem = elem1 + elem2 + elem3 + elem4 + elem5 + elem6 + elem7;
elemMultiplier = 1 + "." + totalElem;
}
In short, I want to be able to turn elemMultiplier into a decimal variable, containing 1.totalElem.
Ok, a really dirty and fast way, replace your
elemMultiplier = 1 + "." + totalElem;
with
elemMultiplier = decimal.Parse("1." + totalElem);
Be ware, this is locale-dependant.
Use this:
String elemMul = "1." + totalElem.ToString();
elemMultiplier = Convert.ToDecimal(elemMul);
Your code shows problem because "." is a string which cannot be converted to decimal implicitly.
Don't concatenate strings. Just do the math:
elemMultiplier =
Convert.ToDecimal(1 + (totalElem / Math.Pow(10, totalElem.ToString().Length)));
(Edited after Gusman noticed a problem.)
I have a listbox which i am populating with data; a string of variable length and 3 ints formatted to fixed lengths.
I can't work out how to get the string text to take up only x characters
i.e.
30 characters worth of space, if string is 5 characters long add 25 characters worth of padding. If string is 10 characters long add 20 characters of padding.
My latest attempt looked like:
int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, " + padding + "}",item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;
But that's still not working: http://i.imgur.com/RfxFCO3.png
This should do the trick.
//int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, -30}", item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;
And if you want Product Names absolutely limited to 30 characters then you'll need to truncate Product Names > 30 characters.
string prodName = String.Format("{0, -30}", item.ProductName.Length > 30 ? item.ProductName.Substring(0,30): item.ProductName);