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.
Related
This question already has answers here:
Truncate Two decimal places without rounding
(24 answers)
Closed 7 years ago.
I have this variable:
Double dou = 99.99;
I want to convert it to a string variable, and the string should be 99.9.
I can do it like this:
string str = String.Format("{0:0.#}", dou);
But the value I got is: 100 which is not 99.9.
So how could I implement that?
PS: This question is marked as duplicated. Yes, they may have the same the solution (although I think that's a workaround), but from different viewpoints.
For example, if there is another variable:
Double dou2 = 99.9999999;
I want to convert it to string: 99.999999, so how should I do? Like this:
Math.Truncate(1000000 * value) / 1000000;
But what if there are more digits after dot?
You have to truncate the second decimal position.
Double dou = 99.99;
double douOneDecimal = System.Math.Truncate (dou * 10) / 10;
string str = String.Format("{0:0.0}", douOneDecimal);
You can use the Floor method to round down:
string str = (Math.Floor(dou * 10.0) / 10.0).ToString("0.0");
The format 0.0 means that it will show the decimal even if it is zero, e.g. 99.09 is formatted as 99.0 rather than 99.
Update:
If you want to do this dynamically depending on the number of digits in the input, then you first have to decide how to determine how many digits there actually are in the input.
Double precision floating point numbers are not stored in decimal form, they are stored in binary form. That means that some numbers that you think have just a few digits actually have a lot. A number that you see as 1.1 might actually have the value 1.099999999999999945634.
If you choose to use the number of digits that is shown when you format it into a string, then you would simply format it into a string and remove the last digit:
// format number into a string, make sure it uses period as decimal separator
string str = dou.ToString(CultureInfo.InvariantCulture);
// find the decimal separator
int index = str.IndexOf('.');
// check if there is a fractional part
if (index != -1) {
// check if there is at least two fractional digits
if (index < str.Length - 2) {
// remove last digit
str = str.Substring(0, str.Length - 1);
} else {
// remove decimal separator and the fractional digit
str = str.Substring(0, index);
}
}
I have a string which contains a number. It can be one with decimals, followed by either a comma or a dot, depending on the user's locale.
The numbers are actually hundredths and I want to convert them to plain old ints. For example, I want strings "14.5" and "14,5000" to end up as int 1450.
It's probably me, but I can't figure out how to correctly convert this number into an int with a corresponding value when the decimals are separated by a comma. I've tried this:
double valueDouble;
double.TryParse(SpecificTemperatureTextBox.Text, NumberStyles.Any,
CultureInfo.CurrentCulture, out valueDouble);
int valueInt = Convert.ToInt32(valueDouble * 100);
But this comes out wrong sometimes. Here are my results:
TextBox value Expected result Converted result
"14" 1400 1400 (good)
"14.0" 1400 1400 (good)
"14.5" 1450 1450 (good)
"14,0" 1400 14000
"14,5" 1450 14500
Am I not using the System.Globalization correctly when I'm converting? I don't want to replace , with . in the string, because that seems too dirty.
How can I do this?
Maybe safest bet would be to try parse input with both cultures, something like this:
private static int ConvertStringValue(string value)
{
decimal valDouble;
var comma = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone();
comma.NumberDecimalSeparator = ",";
comma.NumberGroupSeparator = ".";
var dot = (NumberFormatInfo)CultureInfo.InstalledUICulture.NumberFormat.Clone();
dot.NumberDecimalSeparator = ".";
dot.NumberGroupSeparator = ".";
if (decimal.TryParse(value, NumberStyles.Currency, comma, out valDouble))
{
return Convert.ToInt32(valDouble * 100);
}
else if (decimal.TryParse(value, NumberStyles.Currency, dot, out valDouble))
{
return Convert.ToInt32(valDouble * 100);
}
else
{
return Convert.ToInt32(value);
}
}
Using CurrentCulture will correctly parse numbers with either dot or comma depending on the value of CurrentCulture. But not both simultaneously as in no culture dot and comma are interchangeable.
So, you will have to replace either all commas for dots or vice versa. Then parse with the 'dot separator culture' or 'comma separator culture' setting.
Code first.
taxRateDecimal = 0.0765;
if (taxRateDecimal.ToString().Split('.').Length == 2)
{
outPut = taxRateDecimal.ToString().Split('.')[1].Substring(0, 4);
ReportParameters.Add("TaxRateAsDecimal", "." + outPut);
}
As you can see in the substring I have to hard code my length of 4.
Desired results .0765 as a string.
Here are some scenarios I have gone through.
I have a percent of 7.65.
I want to convert this to decimal, when doing so I do 7.65 / 100.
this gives me 0.0765, but I want just .0765.
If I take 0.0765 and use a split on "." and use length ect..
I actually get for the array [1] a length of 6 and a value of 076500.
Again I only want .0765 or just 0765 and I can add the dot.
Any other ideas that I have not tried?
This will eventually need to be a string since I am passing it in as a prama into SSRS.
You should be able to use a format to create the string:
var taxRateDecimal = 0.0765D;
var reportParameter = taxRateDecimal.ToString(".0000", CultureInfo.InvariantCulture);
The resulting reportParameter is .0765.
Other results for that format are:
0D -> .0000
1D -> 1.0000
1.23456D -> 1.2346
You have to use CultureInfo.InvariantCulture to be sure that the decimal separator is a dot. Otherwise the current culture (which is the default) might specify a comma as the decimal separator.
string.Format will handle this easily.
double taxRateDecimal = 1.0765;
string formattedResult = string.Format("{0:.0000}", taxRateDecimal % 1);
Console.WriteLine(formattedResult); // .0765
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 ",".
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
I'm trying to get my decimals to display with four decimal places. The DB rounds my number to 4 decimal places, but it returns the number with trailing 0s (due to the decimal precision of the field), so something like 9.45670000. Then, when I do this:
string.Format("{0:#,#.####}", decimalValue);
The output I get on the page is 9.4567, which is what I want.
However, if the number returned from DB is 9.45600000, the output after doing the format is 9.456
But what I need to display is 9.4560
How do I format my decimal, so that the number of decimal places is always four?
UPDATE: Also, is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically?
string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
To set the precision dynamically you can do the following:
double value = 9.4560000;
int precision = 4;
string format = String.Format("{{0:N{0}}}",precision);
string valuestring = String.Format(format, value);
string.Format({0:#,#0.0000}, decimalValue);
Use String.Format -
decimal d =123.47
string specifier="{0:0,0.0000}"; // You need to get specifier dynamically here..
String.Format(specifier, d); // "123.4700"
Try this:
string.Format("{0:#,###.0000}", 9.45600000);
Adding the zeroes in the format forces a zero to be output if there is not a digit to put there.
To add the zeroes with the number of zeroes driven programmatically you could do this:
int x = 5;
string fmt = "{0:#,###." + new string('0', x) + "}";
string.Format(fmt, 9.456000000);