Modulo from very large int C# - c#

I'm having a problem with modulo from int which has 31 chars. It seems to bug out on
Int64 convertedNumber = Int64.Parse(mergedNumber); with Value was either too large or too small for an Int64. (Overflow Exception). How to fix it so that modulo doesn't bug out ?
class GeneratorRachunkow {
private static string numerRozliczeniowyBanku = "11111155"; // 8 chars
private static string identyfikatorNumeruRachunku = "7244"; // 4 chars
private static string stalaBanku = "562100"; // 6 chars
public static string generator(string pesel, string varKlientID) {
string peselSubstring = pesel.Substring(pesel.Length - 5); // 5 chars (from the end of the string);
string toAttach = varKlientID + peselSubstring;
string indywidualnyNumerRachunku = string.Format("{0}", toAttach.ToString().PadLeft(13, '0')); // merging pesel with klient id and adding 0 to the begining to match 13 chars
string mergedNumber = numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku + stalaBanku; // merging everything -> 31 chars
Int64 convertedNumber = Int64.Parse(mergedNumber);
Int64 modulo = MathMod(convertedNumber, 97);
Int64 wynik = 98 - modulo;
string wynikString = string.Format("{0}", wynik.ToString().PadLeft(2, '0')); // must be 2 chars
indywidualnyNumerRachunku = wynikString + numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku;
return indywidualnyNumerRachunku;
}
private static Int64 MathMod(Int64 a, Int64 b) {
return (Math.Abs(a * b) + a) % b;
}
}

The max value for Int64 is 9223372036854775807 (19 characters when printed). You will probably want to use BigInteger instead (which was introduced in .NET 4):
public static string generator(string pesel, string varKlientID) {
// I have cut some code here to keep it short
BigInteger convertedNumber;
if (BigInteger.TryParse(mergedNumber , out convertedNumber))
{
BigInteger modulo = convertedNumber % 97;
// The rest of the method goes here...
}
else
{
// string could not be parsed to BigInteger; handle gracefully
}
}
private static BigInteger MathMod(BigInteger a, BigInteger b)
{
return (BigInteger.Abs(a * b) + a) % b;
}

Int64.MaxValue is 9,223,372,036,854,775,807 that's 19 characters. So you just can't fit that in. I suggest looking at this question for working with big numbers.

Try this function instead of "MathMod":
static int ModString(string x, int y)
{
if (x.Length == 0)
return 0;
string x2 = x.Substring(0,x.Length - 1); // first digits
int x3 = int.Parse(x.Substring(x.Length - 1)); // last digit
return (ModString(x2, y) * 10 + x3) % y;
}
(since all of your numbers are positive, there is no point in using Math.Abs, as in your original MathMod function).
Use it this way:
modulo = ModString(mergedNumber,97);
This should works with all versions of .NET since 1.1, without the need of BigInteger.

The answer you are looking for is demonstrated here. It includes various manners to calculate the modulus for huge numbers. I used similar methods as described here for international bank account numbers.
A direct link to someone who has a copy pastable method is here.

Related

How do I combine two integers in C#?

Let's say I have the following code:
int digit1 = 1;
int digit2 = 3;
and I need to combine the two integers, resulting in a floating-point number equal, in this case, to 13.0f. This is probably easy, as I'm new to C# and learning it from a book, but how is it done?
Example:
int digit1 = 3;
int digit2 = 6;
float result = combine_integers (digit1, digit2);
// result = 36
NOTE:
I don't actually need a function. I just did that for the sake of the example.
float combine_integers (int digit1, int digit2)
{
return 10*digit1 + digit2;
}
Example
combine_integers(1, 3) ==>
10 * 1 + 3 ==>
10 + 3 ==>
13
combine_integers(3, 6) ==>
10 * 3 + 6 ==>
30 + 6 ==>
36
If your integers are single digits, then abelenky's answer above is going to do it quickest for you. If they're not single digits, then you could do string.Format() as above, but there's also a couple of edge cases that aren't covered, such as negative values or both values being 0.
The string operations above could produce results such as "00", "5-1", or throw an error for not being able to parse the string result. In the case of {5,-1}, you could end up with 49.
What I would do is cover my bases and assume that if you use a negative number, you want the absolute value. This code also covers the base case of single digits, but gives you some flexibility so that combine_integers(12,34) returns 1234.0f.
static float combine_integers (int digit1, int digit2)
{
int checker = Math.Abs(digit2);
int result = Math.Abs(digit1);
do
{
result *= 10;
checker /= 10;
} while(checker>0);
result += Math.Abs(digit2);
return (float)result;
}
private static float combine_integers(int a, int b)
{
return float.Parse(a.ToString() + b.ToString());
}
https://dotnetfiddle.net/M9Bpwt
Try this code:
int digit1 = 3;
int digit2 = 6;
string concat = string.Format("{0}{1}", digit1, digit2);
float result = float.Parse(concat);

C# String.format a number with dynamic number of significant digits [duplicate]

I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx),
I came up with a neat trick (here as an extension method):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
1.200m.Normalize().ToString();
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.
In my opinion its safer to use Custom Numeric Format Strings.
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
I use this code to avoid "G29" scientific notation:
public static string DecimalToString(this decimal dec)
{
string strdec = dec.ToString(CultureInfo.InvariantCulture);
return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :
public static string DecimalToString(this decimal dec)
{
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string strdec = dec.ToString(CultureInfo.CurrentCulture);
return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
}
Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.
decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;
num1.ToString("0.##"); //13.15%
num2.ToString("0.##"); //49.1%
num3.ToString("0.##"); //30%
I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
Basically
decimal v=2.4200M;
v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.
A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):
public static decimal Normalize(this decimal d)
{
int[] bits = decimal.GetBits(d);
int sign = bits[3] & (1 << 31);
int exp = (bits[3] >> 16) & 0x1f;
uint a = (uint)bits[2]; // Top bits
uint b = (uint)bits[1]; // Middle bits
uint c = (uint)bits[0]; // Bottom bits
while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
{
uint r;
a = DivideBy10((uint)0, a, out r);
b = DivideBy10(r, b, out r);
c = DivideBy10(r, c, out r);
exp--;
}
bits[0] = (int)c;
bits[1] = (int)b;
bits[2] = (int)a;
bits[3] = (exp << 16) | sign;
return new decimal(bits);
}
private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
ulong total = highBits;
total <<= 32;
total = total | (ulong)lowBits;
remainder = (uint)(total % 10L);
return (uint)(total / 10L);
}
This is simple.
decimal decNumber = Convert.ToDecimal(value);
return decNumber.ToString("0.####");
Tested.
Cheers :)
Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?
If for display consider formatting the numbers are x.ToString("")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
If it is just rounding, use Math.Round overload that requires a MidPointRounding overload
http://msdn.microsoft.com/en-us/library/ms131274.aspx)
If you get your value from a database consider casting instead of conversion:
double value = (decimal)myRecord["columnName"];
This will work:
decimal source = 2.4200m;
string output = ((double)source).ToString();
Or if your initial value is string:
string source = "2.4200";
string output = double.Parse(source).ToString();
Pay attention to this comment.
Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
Output:
=>1
=>1.000000023
=>1.000000023
=>
how about this:
public static string TrimEnd(this decimal d)
{
string str = d.ToString();
if (str.IndexOf(".") > 0)
{
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
}
return str;
}
You can just set as:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
The following code could be used to not use the string type:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
Returns 789.5
In case you want to keep decimal number, try following example:
number = Math.Floor(number * 100000000) / 100000000;
Here is an Extention method I wrote, it also removes dot or comma if it`s the last character (after the zeros were removed):
public static string RemoveZeroTail(this decimal num)
{
var result = num.ToString().TrimEnd(new char[] { '0' });
if (result[result.Length - 1].ToString() == "." || result[result.Length - 1].ToString() == ",")
{
return result.Substring(0, result.Length - 1);
}
else
{
return result;
}
}
To remove trailing zero's from a string variable dateTicks, Use
return new String(dateTicks.Take(dateTicks.LastIndexOf(dateTicks.Last(v => v != '0')) + 1).ToArray());
Additional Answer:
In a WPF Application using XAML you could use
{Binding yourDecimal, StringFormat='#,0.00#######################'}
The above answer will preserve the zero in some situations so you could still return 2.00 for example
{Binding yourDecimal, StringFormat='#,0.#########################'}
If you want to remove ALL trailing zeros, adjust accordingly.
The following code will be able to remove the trailing 0's. I know it's the hard way but it works.
private static string RemoveTrailingZeros(string input)
{
for (int i = input.Length - 1; i > 0; i-- )
{
if (!input.Contains(".")) break;
if (input[i].Equals('0'))
{
input= input.Remove(i);
}
else break;
}
return input;
}
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
try this code:
string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
Very simple answer is to use TrimEnd(). Here is the result,
double value = 1.00;
string output = value.ToString().TrimEnd('0');
Output is 1
If my value is 1.01 then my output will be 1.01
try like this
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
and then convert that to float

Calculate checksum in C#

numbers[i] = numbers[i] * 2;
if (numbers[i] >= 10)
{
string t = numbers[i].ToString();
Console.WriteLine(t[0] + " plus " + t[1]+" = "+quersumme(t).ToString());
numbers[i] = Convert.ToInt32(t[0]) + Convert.ToInt32(t[1]);
}
public int quersumme(string n)
{
return n[0] + n[1];
}
The function returns 101 when I enter 7. But 7 * 2 = 14 and quersumme should do 1+4 = 5
t[0] is the character '1', and t[1] is the character '4', which is translated to 49 + 52, hence 101. Check out an ASCII chart to see what I'm talking about.
You could try using the Char.GetNumericValue() function:
return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
You're currently summing the Unicode code points - '1' is 49, and '4' is 52, hence the 101. You want to take the digit value of each character.
If you know that the digits will be in the range '0'-'9', the simplest way of doing that is just to subtract '0' and to use the LINQ Sum method to sum each value:
public int SumDigits(string n)
{
return n.Sum(c => c - '0');
}
Or you could use Char.GetNumericValue(), but that returns double because it also copes with characters such as U+00BD: ½.
Try converting n[0] and n[1] to separate int32's in your quersomme function
You are doing string concatenation in quesumme method.
Should be:
public int quersumme(string n)
{
return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
}
It looks to me like you are trying to enumerate the digits in an int.
Try this to avoid slow and cumbersome parsing and conversion. (Its all relative, I haven't tested performance.)
static IEnumerable<int> EnumerateDigits(int value, int baseValue = 10)
{
while (value > 0)
{
yield return value % baseValue;
value = value / baseValue
}
}
Then, if you want to switch the order into an array
var t = EnumerateDigits(numbers[i]).Reverse().ToArray();
But, if you just want to sum the digits.
var checksum = EnumerateDigits(numbers[i]).Sum()

How do sites like goo.gl or jsfiddle generate their URL codes?

I would like to generate a code like goo.gl and jsfiddle websites (http://jsfiddle.net/XzKvP/).
I tried different things that give me too large of a guid, a repeating alphanumeric code, etc.
I'm thinking I should be able to generate an alphanumeric code based on the Primary Key in my database table. This way it will be non-repeating? The PK is an auto-incremented integer by 1. But not sure that's how it should be done.
I want the code to look random, but it does NOT have to be.
For example, I do NOT want item 1234 in my database to be BCDE and the 1235 item to be BCDF.
Examples:
Notice how the url http://jsfiddle.net/XzKvP/ has a unique 5 character code XzKvP associated to the page. I want to be able to generate the same type of code.
goo.gl does it too: http://goo.gl/UEhtg has UEhtg
How is this done?
The solutions based on a random substring are no good because the outputs will collide. It may happen prematurely (with bad luck), and it will eventually happen when the list of generated values grows large. It doesn't even have to be that large for the probability of collisions to become high (see birthday attack).
What's good for this problem is a pseudo random permutation between the incrementing ID and its counterpart that will be shown in the URL. This technique guarantees that a collision is impossible, while still generating into an output space that is as small as the input space.
Implementation
I suggest this C# version of a Feistel cipher with 32 bits blocks, 3 rounds and a round function that is inspired by pseudo-random generators.
private static double RoundFunction(uint input)
{
// Must be a function in the mathematical sense (x=y implies f(x)=f(y))
// but it doesn't have to be reversible.
// Must return a value between 0 and 1
return ((1369 * input + 150889) % 714025) / 714025.0;
}
private static uint PermuteId(uint id)
{
uint l1=(id>>16)&65535;
uint r1=id&65535;
uint l2, r2;
for (int i = 0; i < 3; i++)
{
l2 = r1;
r2 = l1 ^ (uint)(RoundFunction(r1) * 65535);
l1 = l2;
r1 = r2;
}
return ((r1 << 16) + l1);
}
To express the permuted ID in a base62 string:
private static string GenerateCode(uint id)
{
return ToBase62(PermuteId(id));
}
The Base62 function is the same as the previous answer except that is takes uint instead of int (otherwise these functions would have to be rewritten to deal with negative values).
Customizing the algorithm
RoundFunction is the secret sauce of the algorithm. You may change it to a non-public version, possibly including a secret key. The Feistel network has two very nice properties:
even if the supplied RoundFunction is not reversible, the algorithm guarantees that PermuteId() will be a permutation in the mathematical sense (wich implies zero collision).
changing the expression inside the round function even lightly will change drastically the list of final output values.
Beware that putting something too trivial in the round expression would ruin the pseudo-random effect, although it would still work in terms of uniqueness of each PermuteId output. Also, an expression that wouldn't be a function in the mathematical sense would be incompatible with the algorithm, so for instance anything involving random() is not allowed.
Reversability
In its current form, the PermuteId function is its own inverse, which means that:
PermuteId(PermuteId(id))==id
So given a short string produced by the program, if you convert it back to uint with a FromBase62 function, and give that as input to PermuteId(), that will return the corresponding initial ID. That's pretty cool if you don't have a database to store the [internal-ID / shortstring] relationships: they don't actually need to be stored!
Producing even shorter strings
The range of the above function is 32 bits, that is about 4 billion values from 0 to 2^32-1. To express that range in base62, 6 characters are needed.
With only 5 characters, we could hope to represent at most 62^5 values, which is a bit under 1 billion. Should the output string be limited to 5 characters, the code should be tweaked as follows:
find N such that N is even and 2^N is as high as possible but lower than 62^5. That's 28, so our real output range that fits in 62^5 is going to be 2^28 or about 268 million values.
in PermuteId, use 28/2=14 bits values for l1 and r1 instead of 16 bits, while being careful to not ignore a single bit of the input (which must be less than 2^28).
multiply the result of RoundFunction by 16383 instead of 65535, to stay within the 14 bits range.
at the end of PermuteId, recombine r1 and l1 to form a 14+14=28 bits value instead of 32.
The same method could be applied for 4 characters, with an output range of 2^22, or about 4 million values.
What does it look like
In the version above, the first 10 produced strings starting with id=1 are:
cZ6ahF
3t5mM
xGNPN
dxwUdS
ej9SyV
cmbVG3
cOlRkc
bfCPOX
JDr8Q
eg7iuA
If I make a trivial change in the round function, that becomes:
ey0LlY
ddy0ak
dDw3wm
bVuNbg
bKGX22
c0s5GZ
dfNMSp
ZySqE
cxKH4b
dNqMDA
You can think of the five-letter code as a number in base-62 notation: your "digits" are 26 lowercase and 26 uppercase letters, and digits from 0 to 9. (26+26+10) digits in total. Given a number from 0 to 62^5 (which equals 916132832) (say, your primary key) you can do the conversion to a five-digit base-62 as follows:
private static char Base62Digit(int d) {
if (d < 26) {
return (char)('a'+d);
} else if (d < 52) {
return (char)('A'+d-26);
} else if (d < 62) {
return (char)('0'+d-52);
} else {
throw new ArgumentException("d");
}
}
static string ToBase62(int n) {
var res = "";
while (n != 0) {
res = Base62Digit(n%62) + res;
n /= 62;
}
return res;
}
private static int Base62Decode(char c) {
if (c >= '0' && c <= '9') {
return 52 + c - '0';
} else if (c >= 'A' && c <= 'Z') {
return 26 + c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c - 'a';
} else {
throw new ArgumentException("c");
}
}
static int FromBase62(string s) {
return s.Aggregate(0, (current, c) => current*62 + Base62Decode(c));
}
Here is how to generate cryptographically strong random numbers (you need to add a reference to System.Security):
private static readonly RNGCryptoServiceProvider crypto =
new RNGCryptoServiceProvider();
private static int NextRandom() {
var buf = new byte[4];
crypto.GetBytes(buf);
return buf.Aggregate(0, (p, v) => (p << 8) + v) & 0x3FFFFFFF;
}
This is what I ended up doing
(Updated since Daniel Vérité's answer):
class Program
{
private static double RoundFunction(uint input)
{
// Must be a function in the mathematical sense (x=y implies f(x)=f(y))
// but it doesn't have to be reversible.
// Must return a value between 0 and 1
return ((1369 * input + 150889) % 714025) / 714025.0;
}
private static char Base62Digit(uint d)
{
if (d < 26)
{
return (char)('a' + d);
}
else if (d < 52)
{
return (char)('A' + d - 26);
}
else if (d < 62)
{
return (char)('0' + d - 52);
}
else
{
throw new ArgumentException("d");
}
}
private static string ToBase62(uint n)
{
var res = "";
while (n != 0)
{
res = Base62Digit(n % 62) + res;
n /= 62;
}
return res;
}
private static uint PermuteId(uint id)
{
uint l1 = (id >> 16) & 65535;
uint r1 = id & 65535;
uint l2, r2;
for (int i = 0; i < 3; i++)
{
l2 = r1;
r2 = l1 ^ (uint)(RoundFunction(r1) * 65535);
l1 = l2;
r1 = r2;
}
return ((r1 << 16) + l1);
}
private static string GenerateCode(uint id)
{
return ToBase62(PermuteId(id));
}
static void Main(string[] args)
{
Console.WriteLine("testing...");
try
{
for (uint x = 1; x < 1000000; x += 1)
{
Console.Write(GenerateCode(x) + ",");
}
}
catch (Exception err)
{
Console.WriteLine("error: " + err.Message);
}
Console.WriteLine("");
Console.WriteLine("Press 'Enter' to continue...");
Console.Read();
}
}

Remove trailing zeros

I have some fields returned by a collection as
2.4200
2.0044
2.0000
I want results like
2.42
2.0044
2
I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.
I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx),
I came up with a neat trick (here as an extension method):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.
1.200m.Normalize().ToString();
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.
In my opinion its safer to use Custom Numeric Format Strings.
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
I use this code to avoid "G29" scientific notation:
public static string DecimalToString(this decimal dec)
{
string strdec = dec.ToString(CultureInfo.InvariantCulture);
return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :
public static string DecimalToString(this decimal dec)
{
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string strdec = dec.ToString(CultureInfo.CurrentCulture);
return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
}
Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.
decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;
num1.ToString("0.##"); //13.15%
num2.ToString("0.##"); //49.1%
num3.ToString("0.##"); //30%
I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/
Basically
decimal v=2.4200M;
v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.
A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):
public static decimal Normalize(this decimal d)
{
int[] bits = decimal.GetBits(d);
int sign = bits[3] & (1 << 31);
int exp = (bits[3] >> 16) & 0x1f;
uint a = (uint)bits[2]; // Top bits
uint b = (uint)bits[1]; // Middle bits
uint c = (uint)bits[0]; // Bottom bits
while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
{
uint r;
a = DivideBy10((uint)0, a, out r);
b = DivideBy10(r, b, out r);
c = DivideBy10(r, c, out r);
exp--;
}
bits[0] = (int)c;
bits[1] = (int)b;
bits[2] = (int)a;
bits[3] = (exp << 16) | sign;
return new decimal(bits);
}
private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
ulong total = highBits;
total <<= 32;
total = total | (ulong)lowBits;
remainder = (uint)(total % 10L);
return (uint)(total / 10L);
}
This is simple.
decimal decNumber = Convert.ToDecimal(value);
return decNumber.ToString("0.####");
Tested.
Cheers :)
Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?
If for display consider formatting the numbers are x.ToString("")
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
If it is just rounding, use Math.Round overload that requires a MidPointRounding overload
http://msdn.microsoft.com/en-us/library/ms131274.aspx)
If you get your value from a database consider casting instead of conversion:
double value = (decimal)myRecord["columnName"];
This will work:
decimal source = 2.4200m;
string output = ((double)source).ToString();
Or if your initial value is string:
string source = "2.4200";
string output = double.Parse(source).ToString();
Pay attention to this comment.
Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
Output:
=>1
=>1.000000023
=>1.000000023
=>
how about this:
public static string TrimEnd(this decimal d)
{
string str = d.ToString();
if (str.IndexOf(".") > 0)
{
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
}
return str;
}
You can just set as:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
The following code could be used to not use the string type:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
Returns 789.5
In case you want to keep decimal number, try following example:
number = Math.Floor(number * 100000000) / 100000000;
Here is an Extention method I wrote, it also removes dot or comma if it`s the last character (after the zeros were removed):
public static string RemoveZeroTail(this decimal num)
{
var result = num.ToString().TrimEnd(new char[] { '0' });
if (result[result.Length - 1].ToString() == "." || result[result.Length - 1].ToString() == ",")
{
return result.Substring(0, result.Length - 1);
}
else
{
return result;
}
}
To remove trailing zero's from a string variable dateTicks, Use
return new String(dateTicks.Take(dateTicks.LastIndexOf(dateTicks.Last(v => v != '0')) + 1).ToArray());
Additional Answer:
In a WPF Application using XAML you could use
{Binding yourDecimal, StringFormat='#,0.00#######################'}
The above answer will preserve the zero in some situations so you could still return 2.00 for example
{Binding yourDecimal, StringFormat='#,0.#########################'}
If you want to remove ALL trailing zeros, adjust accordingly.
The following code will be able to remove the trailing 0's. I know it's the hard way but it works.
private static string RemoveTrailingZeros(string input)
{
for (int i = input.Length - 1; i > 0; i-- )
{
if (!input.Contains(".")) break;
if (input[i].Equals('0'))
{
input= input.Remove(i);
}
else break;
}
return input;
}
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
try this code:
string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
Very simple answer is to use TrimEnd(). Here is the result,
double value = 1.00;
string output = value.ToString().TrimEnd('0');
Output is 1
If my value is 1.01 then my output will be 1.01
try like this
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
and then convert that to float

Categories

Resources