How to remove last zeros in decimal [duplicate] - c#

This question already has answers here:
How to ignore value after first decimal point first value if it is 0 else take it if greater than 0?
(2 answers)
Remove trailing zeros
(23 answers)
Closed 5 years ago.
I am trying to remove last zero of a decimal value search a lot for this but all answers in web and stack overflow removing all zeros. My aim to display some zeros in last.
Sample
50.00000000
50.01000000
50.01010000
50.01011000
50.01010100
expected
50.00
50.01
50.0101
50.01011
50.010101
I dont lnow how to do it in c#.
I was tried many things like .ToString("G29"); and other answers available but its all giving me like
50.00
50.01
50.01
50.01
50.01
Please Help..

Try this:
decimal num = 50.00m;
decimal num2 = 50.01010100m;
Console.WriteLine(num.ToString("0.00#########"));
Console.WriteLine(num2.ToString("0.00#########"));
Output:
50.00
50.010101
(Like suggested in comments by "Alex" and "Erno de Weerd")

You could use TrimEnd to remove the last zeros like this:
decimal num = 50.01011000m;
if (num % 1 == 0)
{
return num.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
}
string str = num.ToString().TrimEnd('0');
Console.WriteLine(str);
output:
50,01011
You could also pack it into an extension method:
public static class Extensions
{
public static string ToTrimmendString(this decimal num)
{
if (num % 1 == 0)
{
return num.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
}
return num.ToString().TrimEnd('0');
}
}
and call it like this:
Console.WriteLine(num.ToTrimmendString());

You can try
double num = 50.010110000;
Console.WriteLine(num.ToString("0.0000", CultureInfo.InvariantCulture) );
Please see this for more info https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierPt`

you can try something like this
public decimal removeTrailingZeros(decimal val)
{
return val % 1 == 0 ? Math.Round(val, 2) : val / 1.0000000000000000000000000000000000m;
}
test input
50.00000000m,
50.01000000m,
50.01010000m,
50.01011000m,
50.01010100m,
output
50.00
50.01
50.0101
50.01011
50.010101

Related

Check if a string is percentage value

I'm trying to write this in C#. The requirement is very straightforward - check if a string input is a value within the range from 0 to 100.
I want to make sure the string is either an integer value in the range of 0 to 100 or
a double that's within the same range as well.
So for example, these are the accepted values:
0
50
100
0.1
50.7
100.0
I checked the double.parse method here but not sure if it's the one I'm looking for: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-7.0#system-double-tryparse(system-string-system-iformatprovider-system-double#)
The reason is that it can also parse string like this one: 0.64e2 (which is 64)
Is this something that can be achieved with built-in library already?
Wrote you a little snippet:
// C# function to check if string is a percentage between 0 and 100
public static bool IsPercentage(string s)
{
// regex check if s is a string with only numbers or decimal point
if (Regex.IsMatch(s, #"^\d+\.?\d*$"))
{
double d = Convert.ToDouble(s);
return d >= 0 && d <= 100;
}
return false;
}
Also returns false if the string contains % or has exponential (e).
if my understanding of the Q was correct and exponential representations like mentioned "0.64e2" is unwanted:
static bool IsPercentage(string s)
{
if (Single.TryParse(s, NumberStyles.AllowLeadingSign |
NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out Single n))
return n >= 0 && n <= 100;
return false;
}

How do I compare a value to a decimal using a comma separator? [duplicate]

This question already has answers here:
Comma and (decimal) point: Do they need different handling?
(5 answers)
Closed 9 months ago.
I have some decimal input from my DataGridView; let's say 4,3.
I want to compare if it is between 3,5 and 4,4.
How should I write the numbers 3,5 and 4,4 in my code?
With my current attempt, I get some errors like
; expected
} expected
Operator || cannot be applied
I tried with Cultureinfo but I do not know how exactly use it.
Here is my code so far:
var updateLabStar = db.PatientLab.Where(x => x.BloodUrinId == item.BloodUrinId).FirstOrDefault();
if (Convert.ToDecimal(Result) < 3,5 || Convert.ToDecimal(Result) > 4,4)
{
updateLabStar.Interval = updateLabStar.Result + " *";
db.SaveChanges();
}
How to write decimal literal.
var updateLabStar = db.PatientLab.Where(x => x.BloodUrinId == item.BloodUrinId).FirstOrDefault();
if (Convert.ToDecimal(Result) < 3.5m || Convert.ToDecimal(Result) > 4.4m)
{
updateLabStar.Interval = updateLabStar.Result + " *";
db.SaveChanges();
}

Formatting floating point numbers in C#: decimal separator always visible

How do I get 12. from 12 value with standard .NET string formatting? I've tested 0.### and it does not work.
double number = 12;
string.Format("{0:0.###}", number); // returns "12" not "12."
double number = 12.345;
string.Format("{0:0.###}", number); // returns "12.345"
Currently I've resolved with string manipulation but is it somewhat possible with standard string.Format()?
Thanks.
I think you can first check if the double is actually and integer, and if yes, use a simple string.Format("{0}.", number):
double number = 12;
if (number % 1 == 0)
Console.Write(string.Format("{0}.", number));
C# demo
double number = 12;
string.Format((number % 1 == 0) ? "{0}." : "{0}", number);
Gives 12.
double number = 12.345;
string.Format((number % 1 == 0) ? "{0}." : "{0}", number);
Gives 12.345

How to format number into ten thousands [duplicate]

Is there a way using a string formatter to format Thousands, Millions, Billions to 123K, 123M, 123B without having to change code to divide value by Thousand, Million or Billion?
String.Format("{0:????}", LargeNumber)
There are different ways to achieve this, but for me the easiest and quickest is to use the "," custom specifier
double value = 1234567890;
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,568K
Console.WriteLine(value.ToString("#,##0,K", CultureInfo.InvariantCulture));
// Displays 1,235M
Console.WriteLine(value.ToString("#,##0,,M", CultureInfo.InvariantCulture));
// Displays 1B
Console.WriteLine(value.ToString("#,##0,,,B", CultureInfo.InvariantCulture));
I use this mix of formats in an Extension Method (just add it to your project and enjoy) 😎
public static string ToKMB(this decimal num)
{
if (num > 999999999 || num < -999999999 )
{
return num.ToString("0,,,.###B", CultureInfo.InvariantCulture);
}
else
if (num > 999999 || num < -999999 )
{
return num.ToString("0,,.##M", CultureInfo.InvariantCulture);
}
else
if (num > 999 || num < -999)
{
return num.ToString("0,.#K", CultureInfo.InvariantCulture);
}
else
{
return num.ToString(CultureInfo.InvariantCulture);
}
}
Use:
((decimal)235).ToKMB();
// 235
((decimal)1235).ToKMB();
// 1.2K
((decimal)6271235).ToKMB();
// 6.27M
((decimal)93246571235).ToKMB();
// 93.247B
Notes:
It return more detail for bigger numbers and I like it.
It support negative numbers too. (Thanks to #Dusty for his note in comments.
I write a method for decimal numbers in this example, you can write some override methods for it to support int, long and double to use it without any casting such as:
myIntNumber.ToKMB();
myLongNumber.ToKMB();
myDoubleNumber.ToKMB();
myDecimalNumber.ToKMB();
You can implement a ICustomFormatter that divides the value by thousand, million or billion, and use it like this:
var result = string.Format(new MyCustomFormatter(), "{0:MyFormat}", number);

Regex to validate numbers from 0 to 5 with up to 2 decimals

Hi all I am having a requirement where a textbox should allow numers from 1 to 5 along with decimals
Valid conditons : 1,2,3,4,5
Valid conditions : 0.1,0.02,0.5 ---- 4.99
InValid : -1,-2,-3,-4,-5 or 6 5.1 and so one
I tried this expression ^\d{1}[0-5](?:\.\d{1,2})?$ which didn't worked as expected so can some one help me
Try this
^([0-4]{1}(\.\d{1,2})?|5(.0{1,2})?)$
I think regex is somewhat overkill here, isn't it a simple && will help you with this?
decimal _dec = 0.0m;
if ((_dec >= 0) && (_dec <= 5))
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Invalid");
}
but if the value is a string, use Decimal.TryParse() to check if it a valid decimal number or not,
string _strDecimal = "3.5";
decimal _dec;
bool _valid = Decimal.TryParse(_strDecimal, out _dec);
if (_valid)
(
if ((_dec >= 0) && (_dec <= 5))
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Invalid");
}
)
esle
{
Console.WriteLine("Invalid");
}
^([0-4](\.\d{1,2})?|5)$ might do the trick if you only want to consider numbers with only two decimals, ^([0-4](\.\d+)?|5)$ otherwise.

Categories