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"
Related
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
Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."
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 ",".
I have the following value 48.81, it comes as a string from the database, I need to convert it to decimal, I'm using:
Dim Seconds As Decimal = Convert.ToDecimal((Coordinate.Substring(4, 5)), CultureInfo.InvariantCulture)
I'm receiving 4881D and I need 48,81
Any ideas? I thought CultureInfo.InvariantCulture was going to help me with that
EDIT
The coordinate value is 675900.244.
I'm "spliting" it like this:
Dim Degress As Integer = Coordinate.Substring(0, 2),
Dim Minutes As Integer = Coordinate.Substring(2, 2),
Dim Seconds As Decimal = Convert.ToDecimal((Coordinate.Substring(4, 5)), CultureInfo.InvariantCulture),
Dim Position As Enumerations.EnumCoordinatesPosition = Coordinate.Substring(9, 1)
EDIT
EDIT
EDIT
This is the value of the coordinate in the database
The problem lies in the variable databaseCoordinate, which contains comma instead of dot. InvariantCulture uses comma to separate groups of digits and dot as a decimal symbol. To see this execute the following code:
//outputs '.'
Console.WriteLine(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
//outputs ','
Console.WriteLine(CultureInfo.InvariantCulture.NumberFormat.NumberGroupSeparator);
What you can do about it:
Replace comma with dot before parsing - all your code then will work as expected.
Specify decimal separator for Convert.ToDecimal method like this:
decimal Seconds = Convert.ToDecimal((Coordinate.Substring(4, 5)), new NumberFormatInfo { NumberDecimalSeparator = "," });
Write update script DB for all DB entries with coordinates to use dot as a decimal symbol.
Example - this code gives the results you are expecting:
string Coordinate = "100948.811"; //Note the dot instead of comma
int Degress = Convert.ToInt32(Coordinate.Substring(0, 2)); //10
int Minutes = Convert.ToInt32(Coordinate.Substring(2, 2)); //9
decimal Seconds = Convert.ToDecimal((Coordinate.Substring(4, 5)), CultureInfo.InvariantCulture); //48.81
There is a problem related to the value received from database; and also a problem with your approach.
First, if you expect a decimal value, then store it as a decimal in the database.
And secondly, you are trying to parse a string which shall have at least 9 chars. what you have is only 5 chars.
(Coordinate.Substring(4, 5)) here you are declaring that you are expecting at least 9 chars; what you have is only 5 chars.
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.