forcing four decimal places for double - c#

I need to display particular value to 4 decimal places for sure.
Here is the code
row["Money"] = StringMgt.ToGlobalizationString("N4", dblMoney);
public static string ToGlobalizationString(string format, double dblNumber)
{
return dblNumber.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
Which outputs
1.4305228 to 1.4305 (which is fine!)
0.30704454 to 0.307 (I need to display 4 decimal places consistently)
How do I force it to display four decimal places (ex 0.3070)? I have seen similar posts but did not understand properly.
Thanks.

So the way I understand it you need exactly four decimals, otherwise pad with 0 to the right. So it should be .ToString("0.0000").

I'd use the F-Format specifier:
void Main()
{
double input = 3.213112134;
string result = input.ToGlobalizationString("F4").Dump();
}
public static class Extensions
{
public static string ToGlobalizationString(this double input, string format)
{
return input.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
}
This will return a string with 4 decimal points. Change it to your liking.

Use following format:
row["Money"] = StringMgt.ToGlobalizationString("0.0000", dblMoney);

I have tried all the suggestions. If the output value has zero as the 4th decimal its not displaying it. for ex, instead of 0.3070 it is displaying 0.307. If thh fourth decimal is other than zero, it works just fine.
example:
Input value: 0.511519926
Output: 0.5115
Input Value: 0.45895644
Output Value: 0.459
I took off cultural settings and still it didn't work.
I did this and it worked
ClassA.gridTable.Columns[17].DefaultCellStyle.Format = "#,0.0000";
Thanks all for your valuable inputs.

Related

How can I best limit the decimal places to 5 or shorten the longer ones?

I have a file with various characters and either words as well as numbers. These numbers can be integers like a 1 or 12 (as an example) or they have a comma and countless digits after the comma.
for example:
",{"n":"Box","p":[-4.0,4.0,0.0],"r":[270.0,0.0,0.0],"s":[1.0,1.000006,1.000006],"c":[0.448529363,0.4280135,0.412251264],"m":"wood_14"}"
The file is read with File.ReadAllText and then passed to NewtonsoftJson via JsonProperty accordingly
for example:
[JsonProperty("s")]
public double[] Scale
{
get;
set;
}
For example, with Scale, I want to limit the decimal places to a maximum of 5 digits.
Is this possible and if so, how?
I have been trying for days with different things, but nothing has worked yet.
My idea was to intervene in the string I build first before passing that to Json there. But unfortunately this does not work. I tried it with regular expression like Notepadd++ makes for example.
(edit)
I don't know if you want it to serialize or deserialize. So I made code for both cases. You have to leave one variant or another
public class a
{
private double[] val;
[JsonProperty("s")]
public double[] Scale
{
get { return val;
// or
val?.Select(v => Math.Round(v, 5)).ToArray(); }
set {
val=value;
//or
val = value?.Select(v => Math.Round(v, 5)).ToArray();
}
}
}
if you want it in many properties you can make it as a function
double.ToString() will do it.
const double d = 0.123456789;
string s = d.ToString("G5");
Console.WriteLine(s);
That outputs 0.12346, showing that it rounds the 5 to 6.
Documentation for Double.ToString shows much more detailed examples of how to format numbers.
The number format (i.e. decimal separator) is culture-specific. If you want to use the current culture, then the above will work. If you always want a comma as the decimal separator, you'll have to call the overload that accepts an IFormatProvider for the specific culture.

What is the percentage format string to always display the sign?

I want to display 0.12345 as "+12.3%". Format string "P1" or "p1" gives "12.3%". I have tried both "+P1" and "+p1" to no avail.
string sFoo = 0.12345.ToString("P1");
Update
I should have emphasized that I always want the proper sign, not "+". If the number is -0.12345, "P1" works exactly as I want: "-12.3%".
Not quite using P1, but same result:
0.12345.ToString("+#.#%;-#.#%");
If you prefer at least one leading digit (e.g. "+0.23%" instead of "+.23%"):
0.12345.ToString("+0.#%;-0.#%"));
Same for trailing digits (e.g. "+14.0%" instead of "+14%"):
0.12345.ToString("+0.0%;-0.0%"));
Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#the--section-separator
var num = 0.12345;
var sign = num > 0 ? "+" : "";
var output = $"{sign}{num.ToString("P1")}";
I'm afraid there is no format string to display the positive sign. I've searched in NumberFormatInfo if some custom format could accept this, but with no avail.
You can however build some extension methods to fit your needs :
public static string ToSignedPercent(this double input)
{
return $"{(input >= 0 ? "+" : "")}{input.ToString("P1")}";
}
// ...
Console.WriteLine((0.12345).ToSignedPercent()); // +12.3%
Console.WriteLine((-0.6789).ToSignedPercent()); // -67.9%
Fiddle
Put the following in your main method. basically this approaches just sets the variable sFoo to have format of percentage with two decimals.
string sFoo = String.Format("Value: {0:P2}.", 0.12345); // formats as 12.35%
Console.WriteLine(sFoo);

Remove Decimal form String if equals to ".00"

Im having alot of problems trying to take out the decimal part of my string,
the string comes from a var type in my view like this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro))**
temp.Rubro is my String part that can be ".00" or ".XX"
however i need to take the decimal part of the string only when its value is ".00"
since i have some values of the dashlist have important decimal parts.
Is there a way to take the decimal part of a string only if it equals to ".00"???
The output im trying to get is:
From XX.00 -> XX
From XX.12 -> XX.12
both kinds are on my list
Try this:
var temp = dashList[index];
#PrintSection(actualDate, Model, String.Format("{0:0.000}", temp.Rubro).Replace(".00", ""))
You can try using
String.Format("{0:G29}", decimal.Parse(temp.Rubro)))
Whereas all the below formats achieve the same results.
string.Format("{0:G29}", decimal.Parse("2.00"))
decimal.Parse("2.00").ToString("G29")
2.0m.ToString("G29")
You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).
Simple trick...
You can parse the string and it will automatically remove the decimal places
try following
private static void ParseDouble()
{
string sDouble = "12.00";
double dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
sDouble = "12.14";
dValue = double.Parse(sDouble);
Console.WriteLine(dValue.ToString());
}
Your output will be
12
12.14
Hope this helps.
I will suggest you to use accounting.js plugging which is pretty straightforward. I have used it in some projects and as of today I cannot complain. Otherwise, you could do something like this,
var x = temp.Replace(".00","").Trim();

String Format Returns Unexpected Results

I have a simple class that contains a property Format which is set to any given format specifier. I then use the property of this class to, as the name suggest, format the string.
Take the following example:
public class FormatDefinition {
public string Format { get; set; }
}
class Program {
static void Main() {
var formatDefinition = new FormatDefinition {
Format = "N"
};
var number = 20.5;
var formatOne = string.Format("{0:" + formatDefinition.Format + "}", number);
var formatTwo = string.Format("{0:formatDefinition.Format}", number);
var formatThree = $"{number:formatDefinition.Format}";
Console.WriteLine(formatOne); // 20.5
Console.WriteLine(formatTwo); // formatDefinition21Format
Console.WriteLine(formatThree); // formatDefinition21Format
Console.ReadLine();
}
}
Can someone please explain why formatTwo and formatThree have a result of formatDefinition21Format? It seems the period . is replaced by the formatted number.
You are specifying a custom numeric format string consisting of the string "formatDefinition.Format".
This is taken to mean constant string "formatDefinition" followed by the decimal point (and therefore the entire number goes here) followed by constant string "Format".
The number is rounded to zero decimal places because there are no digits specified after the decimal point.
The string formatDefinition.Format is not interpreted as C# code.
According to the documentation for Custom Number Format Strings:
For fixed-point format strings (that is, format strings that do not
contain scientific notation format characters), numbers are rounded to
as many decimal places as there are digit placeholders to the right of
the decimal point.
It's because you have a decimal point with no digit placeholders to its right. You're telling it to round the number to zero decimal places - in other words, round to the nearest whole number.
These are all functionally the same - all return a22b.
string.Format("{0:a.b}", 21.5);
string.Format("{0:a0b}", 21.5);
string.Format("{0:a0.b}", 21.5);
Here's a DotNetFiddle.

C# Get exact string formation from 'double' type

As I'm working on C#, I have one field named 'Amount'.
double amount = 10.0;
So, I want the result like '10.0' after converting it to string.
If my value
amount = 10.00, then I want result '10.00' after converting it to string.
So, Basically I want exact result in string as it is in double type. (With precisions).
Thanks in advance.
string result = string.Format( "{0:f2}", amount );
What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.
string amountString = amount.ToString("N2");
"N2" is the format string used as the first parameter to the .ToString() method.
"N" stands for number, and 2 stands for the number of decimal places.
More on string format's here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
As #Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:
static public string GetPrecisionString( double doubleValue, int precision)
{
string FormattingString = "{0:f" + precision + "}";
return string.Format( FormattingString, doubleValue);
}

Categories