Math.Floor to x digits after decimal - c#

I need to display two digits after decimal point while rounding to floor as a percentage. I wrote out this code to do so, but this looks too complex, is there another more effecient way of doing this?
double decimalPlacesFactor =Math.Pow(10, numberOfDigits+2);
percentage = Math.Floor((NumA/NumB)*decimalPlacesFactor)/decimalPlacesFactor *100;
The output should look like
99.78 %

Use the ToString() methode to convert your number to a string. Display it as a floating point with X digits by using the argument "FX". e.g. "F2" for two digits
string percentage = Math.Floor(NumA/NumB).ToString("F"+numberOfDigits);

Depends on how you want to display the percentage value, but I am guessing you'll want to show string of the percentage? What about:
string percentage = Math.Floor(NumA/NumB).ToString("0.00");
Console.WriteLine(Math.Floor(2.3).ToString("0.00")); //this will output 2.00
If you want to make the number of digits after decimal configurable you could create the masking string beforehand, with something like this:
private string CreateMaskingString(int numberOfDigits)
{
var sb = new StringBuilder("0.");
sb.Append(new string('0', numberOfDigits));
return sb.ToString();
}
And usage would look like this:
Console.WriteLine(Math.Floor(2.3).ToString(CreateMaskingString(2))); //this will output 2.00
A much more simple and elegant solution looks like this, as has been pointed out by RomCoo:
string percentage = Math.Floor(NumA/NumB).ToString("F" + numberOfDigits);
What does the "F" mean here? You can read the explanation here. But basically:
The fixed-point ("F") format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative.

Related

string format money , [duplicate]

I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")

How to display up to two digits at max but can show less?

How do I format a cell in a grid that is treated like text to be zero, one, or two digits depending on what the value is but to cut it to two digits if it has more?
If the value is 25 we display 25.
If the value is 26.3 we display 26.3.
If the value is 27.59 we display 27.59.
If the value is 28.124 we display 28.12.
If the value is 11.1111111 we display 11.11.
Does this make sense?
I'm using C#, MVC, and javascript/jquery.
If you do not want to round the value, you can do two different things:
//using String.Format()
string.Format("{0:#.##}", someValue)
//using ToString()
someValue.ToString("#.##")
Working fiddle here
If your value is not in a double/decimal then you can either manipulate the string by checking the index of the decimal point and trimming the string to 1 or 2 indexes to the right of that. However it might just be easier to parse the value into a new double then let the string formatting take it from there.
In C# you can user Math.Round function
decimal d = 28.1234;
Var a = Math.Round(d,2);
a will be 28.12
So because you said it's like a text you start with a string :
string text = "25.1234";
Then you can parse it to a double so you can round it :
double number = double.Parse(text);
Then you finish by rounding the value to the decimal you need and transforming it to a string :
text = Math.Round(number, 2).ToString();

How to use String.Format to format a number with comma separators and floating decimal point?

Suppose I have a list of decimal numbers that I must format with a comma every three places, plus the appropriate number of digits after the decimal point. I want to use the .net string.Format method.
I want it to work like this:
string format = ???;
string s1 = string.Format(format, "1500"); // "1,500"
string s2 = string.Format(format, "1500.25"); // "1,500.25"
string s3 = string.Format(format. "3.1415926358979"); // "3.1415926358979"
I have seen other answers where the digits after the decimal are either limited to a fixed number of digits or truncated entirely, but this doesn't work for my application. I want to add the comma-separator to the whole part of the number, but keep the digits after the decimal exactly as they are.
First problem, you need to parse your strings before you can format them. There maybe some lose of precision. Then you need to decide what your maximum amount of precision you need is. Then you can do something like this:
string format = "{0:#,##0.#############}";
string s1 = string.Format(format, double.Parse("1500")); // "1,500"
string s2 = string.Format(format, double.Parse("1500.25")); // "1,500.25"
string s3 = string.Format(format, double.Parse("3.1415926358979")); // "3.1415926358979"
The # after the decimal place is a place holder for a decimal digit. If there are no more digits it won't show trailing zeros.
If being limited to a number of decimal places or possibly losing precision when converting to double. You could do something really cludgy like this:
public static string DecimalFormatCludge(string original)
{
var split = original.Split('.');
return string.Join(".", (new [] { int.Parse(split[0]).ToString("#,##0")}).Concat(split.Skip(1)));
}
This will split on the . in the string, parse the first part as an int, convert it back to a string correctly formatted and then just stick the decimal part back on (if there is one)
something like this?
string s1 = format.ToString("#,##0.00");
The format is something like this:
string format = "{0:#,##.##################}";

C# convert string to decimal 4dp

I need to take a string object and convert it to a decimal to 4 dp.
So for example:
string val = "145.83011";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
bring back 145.8301 - good
However:
string val = "145.8300";
decimal sss = Math.Round(Convert.ToDecimal(val), 4);
brings back 145.83
I need it to be 145.8300
I need it in a decimal format so can't use string format options.
Thanks
rob
One option would be to use string manipulation three times:
Parse the original text to a decimal value (this will preserve the original number of decimal places)
Use string formatting to end up with a string with exactly 4 decimal places. (Math.Round ensures there are at most 4DP, but not exactly 4DP.)
Parse the result of the formatting to get back to a decimal value with exactly 4DP.
So something like this:
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
I recoil from using string conversions like this, but the alternatives are relatively tricky. You could either get the raw bits, split out the different parts to find the mantissa and scale, then adjust appropriately... or you could potentially work out some sequence of arithmetic operations to get to the right scale. (Jeppe's approach of multiplying by 1.0000m may well be entirely correct - I just don't know whether it's documented to be correct. It would at least be worth adding in appropriate tests for the sorts of numbers you expect to see.)
Note that the above code will perform round up on halves, as far as I can tell, so 1.12345 will be converted to 1.1235 for example.
Sample with output in comments:
using System;
using System.Globalization;
class Test
{
static void Main()
{
Console.WriteLine(Force4DecimalPlaces("0.0000001")); // 0.0000
Console.WriteLine(Force4DecimalPlaces("1.000000")); // 1.0000
Console.WriteLine(Force4DecimalPlaces("1.5")); // 1.5000
Console.WriteLine(Force4DecimalPlaces("1.56789")); // 1.5679
}
public static decimal Force4DecimalPlaces(string input)
{
decimal parsed = decimal.Parse(input, CultureInfo.InvariantCulture);
string intermediate = parsed.ToString("0.0000", CultureInfo.InvariantCulture);
return decimal.Parse(intermediate, CultureInfo.InvariantCulture);
}
}
Both Convert.ToDecimal and decimal.Parse do preserve trailing zeroes in the string (a System.Decimal can have at most 28-29 digits in total, so in most cases there's still room for all the trailing zeroes).
And Math.Round(..., 4) preserves trailing zeroes up to the fourth place after the decimal period.
Therefore the premise of the question is wrong. Your example does bring back what you want.
In any case, consider specifying the overload that takes in an IFormatProvider as well, and give CultureInfo.InvariantCulture as argument. Then the conversion is independent of the local culture.
If instead you want to handle strings like "145.83" and append trailing zeroes that were not in the string, use:
string val = "145.83";
decimal sss = Math.Round(
decimal.Parse(val, CultureInfo.InvariantCulture) * 1.0000m,
4);
Epilog: If you don't like multiplying and dividing by numbers like 1.0000m, use decimal.GetBits to get the internal representation. Adjust the integer "part" by multiplying or dividing by the appropriate power of ten, and adjust the scale "part" by subtracting or adding the corresponding number. The scale counts the number of places to move the decimal point to the left, starting from the 96-bit integer.

Remove decimal from currency

I am converting data for an export.
The file shows data in cents, not dollars.
So 1234.56 needs to be printed as 123456
Is there a way to do that with string.Format?
Or is the only solution to multiply by 100?
You can use string.Replace(".", string.empty). But that isn't exactly localized. You could add in cases where you check for "," as well for international currency. But that's what I would do.
[Edit]
Also just found this:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
The "N" numeric specifier allows you to change the symbol used to separate whole number and decimal parts.
<code>
decimal num = 123.456m;
NumberFormatInfo ci = CultureInfo.CurrentCulture.NumberFormat;
ci.CurrencyDecimalSeparator = " "; // You can't use string.Empty here, as it throws an exception.
string str = num.ToString("N", ci).Replace(" ", string.Empty);
</code>
Something like that should do the trick, and is localized!
That's a rendering issue. Certainly multiplying by 100 to get cents will do the job.
The United States uses the decimal point to separate dollars from cents. But not all countries do that. Your "multiply by 100" solution is only correct for currencies that use 100 fractional units to represent a single whole. (Not the case in Japan for yen.)
If it is that simple, just do String.Replace('.','');
if you know that the values will always have 2 Decimal Positions then do this it's very simple
var strVar = 1234.56;
var somevalues = string.Format("{0:######}", strVar * 100);
output = 123456

Categories