I have an array that contains product names and prices such as thingy25.00 but when I run this line of code below I get 25 and all zeroes are gone. I need to keep two decimal point after the period so basically 25.00.
price[i] = Convert.ToDouble(product[i].Substring(7, 4));
It will once you format the output like this:
var s = price[i].ToString("#,##0.00");
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
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"
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."
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 have a senario where I am converting numbers to words and I have suceeded in it, but I found one scenario where it's not working. If I enter the number as "10", it displays "ten". Also, "10.2" will display "ten point two". However, if I enter "10.0" it will not display as "ten point zero".
For seperating the whole number part from the decimal part I usually split the number by '.', but if I enter a number like "10.0", the string array will contain only "10" and not the "0"
The spitting part which I have done is given below:
string[] number = Convert.ToString(context.NumberToTranslate).Split('.');
To test if your number is an integer w/o decimal point you could try and parse it with
int tmpInt;
bool isInteger = Int32.TryParse(num.ToString(), out tmpInt);
If it is an integer just convert the number to your string representation otherwise preserve the digit after the decimal point no matter what using a custom format string:
string number = num.ToString("#.0");
The same issue can arise if your number is less than 1, so you can use the zero placeholder for the digit before the decimal point as well:
string number = num.ToString("#0.0");
Also see Custom Numeric Format Strings
Actually numbers after point is lost if the number, even i the number is a Float or Double.
The solution is to use decimal Type for these numbers, it preserves the 0 after decimal.
Example:
Console.WriteLine(Convert.ToString(10.0M));
Output:
10.0
Febin:
It seems like an order of operations issue. Try doing the splitting before the converting"
var parts = ("10.0").Split('.'); //or context.NumberToTranslate
parts[0] //"10"
parts[1] //"0"
//Convert
string[] number = Convert.ToString(parts);
You don't have to break it out completely, but I did that to show you can split "10.0" and then do what you want with it.
One thing you could do is compare your number to itself cast to an integer to determine if you need to append zero to the string that you're generating.
Something along the lines of:
var n = 10.0f;
if(n == (int)n) {
Console.WriteLine("zero");
}