Float value should have 2 decimals - c#

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.

Related

C# Convert currency to string, remove decimal point but keep decimals, prepend 0s to have fixed width

How do I convert money amount like this
38.50
, to fixed width like this
000003850
I dont want to add commas and decimal places as some suggested answers here are explaining how to do. Neither do I want to remove decimals, I only want to remove decimal point.
You can use string.Format() with custom format specifiers. See details here.
double dollars = 38.50; // your value
int temp = (int)(dollars * 100); // multiplication to get an integer
string result = string.Format("{0:000000000}", temp);
// Output: 000003850
Figured it out thanks to #ReedCopsey at How to remove decimal point from a decimal number in c#?.
decimal amount = 38.50m;
int fixed_amount = (int)Math.Truncate(amount * 100);
Console.WriteLine(fixed_amount.ToString("D9"));
OUTPUT:
000003850

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

Rounding to 2 decimal places but keeping 4 decimal places in C#

I would like to round a number to 2 decimal places but also keep the trailing 2 zeros so for example 425.1382 to 425.1400
I've tried below examples but it doesn't seem to work
var amount = Math.Round((value * rate), 4);
profit = Decimal.Parse(amount.ToString("0.####"));
or
var amount = Math.Round((value * rate), 4);
profit = Decimal.Parse(amount.ToString("0.##00"));
When you convert to a numeric type you give up all unnecessary digits. You need to convert the Decimal to a String before displaying.
The _invoicingCurrencyProfitAmount = Decimal.Parse(profitAmount.ToString("0.####")) line is returning a decimal. Decimal does keep all zeroes, the problem is 100% in where are you printing the value.
If you are trying to write this in Console
Console.Writeline("{0:F4}", _invoicingCurrencyProfitAmount);
where {0:F4} means "Format as fixed-point", with four numbers after point. Of course, you can use this anywhere by using string.Format.
var _profitAmount = Math.Round((saleMarginValue * exchangeRate), 4);
_invoicingCurrencyProfitAmount = Decimal.Parse(profitAmount.ToString().PadRight(2,'0'));
var d = 425.1382.ToString("0.##") + "00"; // "425.1400"

String Format for Thousand separators

Is there a way using String Formatter I can achieve the following:
$52,152 to $52.1
I have a series of values that are all thousands and I will like to display them in the above format.
Thanks
This works for $52.2, using the , number scaling specifier:
string.Format("{0:$0,.0}", 52152);
If you really want 52.1, you’ll probably have to do it “manually”; sorry. All custom formatting strings seem to round.
In your case the non-formatted versions of your 2 numbers are inherently different
52152 != 52.1
A better solution might be to send the correct numbers to the UI but if not, you can use the , scaling specifier - http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierTh
void Main()
{
decimal x = 52152M;
var a = string.Format("{0:C}", x); //Current Format in Local Culture
Console.WriteLine(a); //Prints €52,152.00
var b = string.Format("${0:00000}", x); //Custom Format, no decimals
Console.WriteLine(b);//Prints $52152
var c = string.Format("${0:###,###,###}", x); //Custom Format, no decimals + 1000 seperators
Console.WriteLine(c);//Prints $52,152
var d = string.Format("${0:###,###,.0}", x); //Custom Format, 1 decimal place, 1000 seperators to support values over 1 million
Console.WriteLine(d);//Prints $52.2
}
Something like this?
string input = "$52,152";
var number = long.Parse(input, NumberStyles.Currency);
string result = (number / 100L / 10m).ToString("C1");
Explanation. First division is an integer division that truncates. Second division is a System.Decimal division.
This assumes a culture (for example new CultureInfo("en-US")) where the currency sign is "$" and the thousands separator is ",".

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

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));

Categories

Resources