C# three part format display original value [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am trying to display the original value in C# three part display format. I got unexpected result + 29291221321. I am expecting + 29.12121321. Is this a bug or what am I doing wrong?
double value1 = 29.1221321;
string formattingString = $"+ {value1}; - {value1}; 0";
// returns "+29.1221321; -29.1221321; 0"
Console.WriteLine(value1.ToString(formattingString));
// returns "+ 29291221321"
Please refer to why i call ToString at the end. It is something known as three part format to separate outcome quickly based on +, - and 0 value
https://diptimayapatra.wordpress.com/2014/01/13/3-part-format-of-numbers-in-c/
Note:
I am not expecting to hardcode by specify x numbers of # after decimal places. Please advise if there is a better method of displaying the original decimal value in three part format
string formattingString = "+ #.############; - #.############; 0";

Please advise if there is a better method of displaying the original decimal value in three part format
# is already the best way to express what you want, since it will omit non-significant zeros at the end. A double has about 15 to 17 significant digits, so you can put 17 # at the end of your format specifier to get the original value.
double value1 = 1.23456;
string formattingString = "+ #.#################; - #.#################; 0";
Console.WriteLine(value1.ToString(formattingString));
Console.WriteLine((-value1).ToString(formattingString));
Console.WriteLine(0.ToString(formattingString));
Output (note the leading spaces, because you have spaces in your format specifier):
+ 1,23456
- 1,23456
0
Check that for a double value with more digits
double value1 = 1.2345678901234567890123; // too many digits for a double
and compare it to the output of
Console.WriteLine(value1);

You're putting the value into the format specifier instead of your specifier:
string formattingString = $"+ {value1}; - {value1}; 0";
Your snippet should instead look like this:
double value1 = 29.1221321;
string formattingString = $"+ #.############; - #.############; 0";
Console.WriteLine(value1.ToString(formattingString));
With the added understanding that you do not want to use the hard coded number of decimal places (which is understandable given the precision available with double), I'm not aware of a way using interpolation. I'd recommend a simple extension method for it:
public static string ToSignedString(this double value) {
if (value < 0)
return $"-{value}";
else if (value > 0)
return $"+{value}";
return "0";
}
I don't typically recommend extension methods, but I believe your reasoning for not wanting hard coded decimal places is perhaps the need for the code to be concise due to heavy use.
double value = 29.1221321;
Console.WriteLine(value.ToSignedString());
Not the most graceful solution, but it would work.

You try to reformat Value1 another time in the Console.WriteLine
Change it to :
Console.WriteLine(formattingString);

Related

cannot convert "-1,37739,38739" to integer C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
I have tried to convert the string "-1,37739,38739" into an integer in order to pass the integer into a predefined method.
I'm getting System.FormatException: 'Input string was not in a correct format.'
var dc1 = Convert.ToInt32(item.Path.ToString());
he item.Path come from a query value predefined as a string, I have to convert that string into an integer, it's coming with the above mentioned string value
-1,37739,38739 is - reformatted - -13,773,938,739; int.MinValue (the most negative value a 32-bit signed integer can represent) is -2,147,483,648 - so: it won't fit. Try long instead of int, i.e. ToInt64.
You may also need to specify an explicit culture (depending on your locale), and be a little more... forgiving re group separators:
if (long.TryParse("-1,37739,38739",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out var val))
{
Console.WriteLine(val); // works
}
This not a surprise.
1st : -1,37739,38739 is not properly formatted. This should be either
-13773938739
or
-13,773,938,739 (or -13 773 938 739 depending on your locale)
2nd: Int32 is an integer based on 32 bits which gives min and max values -2,147,483,648 and 2,147,483,647
See documentation here Int32
If you want to convert a string which is not controlled upfront, then I would suggest you "clean" it
string item = "-1,37739,38739";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
item = rgx.Replace(item, "");
and maybe convert to Int64
var dc1 = Convert.ToInt64(item);
If you want to avoid exception, you also can try to parse the string (once cleaned)
if (Int64.TryParse(item, out var dc1))
{
// doSomething
}
else
{
// handle error
}
string item = "-1,37739,38739";
var munyamatindike=Convert.ToInt32(item);
the above code snippet should fix the error.enter image description here

How to check values numbers after the decimal point [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 5 years ago.
I have tried looking for a similar question here but I can only find how to count the number of decimal places.
What I want to know is: how do I find the value of the decimal places that are >0?
For example, if we have:
decimal value = 1.920m;
decimal value2 = 1.900m;
How do I check if the values after the decimal point are >0?
I want to be able to check this and restrict the display accordingly so I can display something like this:
1.92
1.9
Essentially you want to display the value with the max number of decimal places available and remove the trailing zeros. This is the easiest way to do it:
Console.WriteLine(value.ToString("G29")); // Output 1.92
Alternate solution (which works for numbers smaller than 0.00001m unlike the above solution). Though this doesn't look as neat as the previous solution using G29, this works better since it also covers numbers smaller than 0.00001:
Console.WriteLine(value.ToString("0.#############################")); // Output 1.92
We are using G29 since 29 is the maximum available digits for a decimal. The G or General Format Specifier is used to define the maximum number of significant digits that can appear in the result string. Any trailing zeros are truncated using this format specifier. You can read more about it here.
Input: 1.900m
Output: 1.9
Input: 14.571428571428571428571428571M
Output: 14.571428571428571428571428571
Input: 0.00001000000m
Output: 1E-05 (Using first solution G29)
Output: 0.00001 (Using second solution)
If i understand you right you can do something like this:
double x = 1.92;
x-=(int)x;
while(x%1>0){
x*=10;
}
Console.WriteLine(x);
output:
92
now you can check what you want on this number
If you want to convert to decimal only use this
static decimal? RemoveTrailingZeros(this decimal? value)
{
if (value == null) return null;
var format = $"0.{string.Join(string.Empty, Enumerable.Repeat("#", 29))}";
var strvalue = value.Value.ToString(format);
return ConvertToDecimalCultureInvariant(strvalue);
}
static decimal? ConvertToDecimalCultureInvariant(this string value)
{
decimal decValue;
if (!decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decValue))
{
return null;
}
return decValue;
}
Since the precision of a decimal is 29 hence Enumerable.Repeat("#", 29).
And use it as
var result = RemoveTrailingZeros(29.0000m);

How to convert a double value to string without rounded [duplicate]

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

How do I trim the "0." after I do modulo 1 on a double variable

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."

How to round and format a decimal correctly? [duplicate]

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

Categories

Resources