C# Not Rounding Double - c#

When I pass this object back as JSON, it looks like this:
0.000000000000000e+000
My code in C# is:
// get adjustments for user
IEnumerable<Severity> existingSeverities =
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
id = s.severity,
adjustment = Math.Round((double)s.adjustment, 2, MidpointRounding.AwayFromZero).ToString(),
isT_E = (bool)s.isTimeAndExpense
};
How can I make it just round to two decimal places (0.00)?

Use;
dec.ToString("#.##");
See this answer for more information
If it's a nullable double in a Console app do;
double ? d = 2.22222;
Console.WriteLine(d.Value.ToString("#.##"));

I think that you are confusing two things. The "real" number is not what you see. The real number is stored internally in a binary format. The decimal digits that you see do not exist in this internal format. What you see is the conversion of this value to a decimal representation as a string.
The conversion of any internal binary representation to a human visible string is called formatting. The Round function does not format. See this example:
double x = 0.123456000000000e+000;
double y = Math.Round(x, 2, MidpointRounding.AwayFromZero);
// y ====> 0.120000000000000e+000;
The rounding function changes the internal value. What you need is probably not to change the value but to display the unchanged value with only two digits:
string formattedValue = x.ToString("N2");
If you are deling with currencies, use decimal rather than double. decimal uses a binary encoded decimal format internally. Values like 1/10 cannot be represented precisely as binary number in a computer just like 1/7 cannot be represent precisely in decimal notation (0.142857142857...). But 1/10 has an exact internal representation when stored as a decimal.

Turns out, this was a LINQ to SQL issue. I did this, and it works...
// get adjustments for user
IEnumerable<Severity> existingSeverities =
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
id = s.severity,
adjustment = roundtest(s.adjustment.GetValueOrDefault()),
isT_E = (bool)s.isTimeAndExpense
};
// test method...
public string roundtest(double num)
{
return num.ToString("#.##");
}

Try this:
// get adjustments for user
IEnumerable<Severity> existingSeverities =
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
id = s.severity,
adjustment = s.adjustment.GetValueOrDefault().ToString("0.##"),
isT_E = (bool)s.isTimeAndExpense
};
-Edit-
I think that maybe you will need to have the Severity class have a Property that takes a double and saves a string to Severity.adjustment, like so:
Severity
{
//rest of class as normal
public double SetAdjustment
{
set { adjustment = value.ToString("0.00"); } }
}
}
-Edit, part 2-
// get adjustments for user
IEnumerable<Severity> existingSeverities =
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
id = s.severity,
SetAdjustment = s.adjustment.GetValueOrDefault(),
isT_E = (bool)s.isTimeAndExpense
};
The rest of your code should not need to be changed, it should still use (Severity variable).adjustment as normal. This is just to get around the fact that there is not guaranteed way to translate .Net's Standard Numeric Format Strings into SQL's Convert, much less any custom formatting.

Related

Subtracting int from double leads to an error

I have an int and a double, but as soon as I try to subtract the integer from the double, the following error is thrown:
Input string was not in a correct format.
Now lets look at the code:
double TotalNoRegis = values.Sum(); // This is a LIST and its = 1569
string otherFe ="600";
double totalafter;
if(otherFe != string.Empty || otherFe!= "") // This part works fine
{
totalafter = TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown
}
What am I doing wrong here? I looked at this Example, which is basically the same thing: int x = 1 and int y = 2 and then int this = x-y;
Please let me know if you know the issue here.
What am I doing wrong here?
Lots.
if(otherFe != string.Empty || otherFe!= "") // This part works fine
That's nonsensical code. string.Empty and "" are the same string.
Instead use
if (!string.IsNullOrEmpty(otherFe))
Moving on:
totalafter = TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown
You claim that the error is the subtraction, but it is not. The problem is in the ToInt32. You are passing some other string than the one you are showing.
The way I like to do this is by making an extension method:
static public class Extensions
{
public static int? ParseAsInteger(this string s) {
if (string.IsNullOrEmpty(s)) return null;
int i;
return int.TryParse(s, out i) ? (int?)i : (int?)null;
}
// Similarly write `ParseAsDouble` and so on.
}
Now you have an extension you can use:
double? totalAfter = TotalNoRegis - otherFe.ParseAsInteger();
(Or ParseAsDouble, or whatever.)
If otherFe was valid, then totalAfter has the total; if it was not, then it is null.
The lesson here is: move the type conversion logic into its own method which you can independently test. Then the logic at the call site of that method becomes simpler and easier to follow.
You should use an integer instead of a double, especially if you don't have a reason to use the double. So to rectify, you could simply do the following.
int total = values.Sum();
var other = "6000";
if(!string.IsNullOrEmpty(other))
if(int.TryParse(other, out int subtractor))
total -= subtractor;
If you require a double, then use but if you don't why bother? Also, you are subtracting fifteen hundred items from six thousand, your total after will always be negative or often be negative. Is that your desired intent?
Something to note, with the TryParse if it fails it'll skip the subtraction rather than fail like parse or convert would do. Also do you want the sum of the list or count?

How to pass a floating point value using json from mvc controller to jquery without truncating zero

I have function to calculate price as follows:
public ActionResult updatePrice(int pageCount,int detid ,int spec)
{
double amt = 0.00;
double final = 0.00;
using(APM context = new APM())
{
var lst = (from s in context.M_Spec
join p in context.M_SpecDetails on s.ID equals p.SpecID
where p.SpecificationID == spec && p.SpecID == detid
select new
{
amount = (double) p.Rate
}).ToList();
foreach( var s in lst)
{
amt = (pageCount - 10) * (s.amount) ;
}
var def = (from s in context.M_Spec where s.ID == detid
select new
{
defamt = (double)s.DefaultCost
}).ToList();
foreach (var s in def)
{
final = (s.defamt) + amt;
}
}
return Json(new { success = true, Amount = final});
}
Finally get the answer like final = 2130.0 and I passed it to the ajax success using json as above and I get the result at ajax success as 2130.How can I overcome this problem?
When you pass in a value type it contains only meaningful digits, zeros after decimal point are being dropped. Also for value types, .NET has cultural based formatting. The way you can get your wanted result by either passing a plain string or forwarding string format a long side with value.
The zeroes after decimal 2130.0 are considered insignificant while the JSON conversion here, therefore are dropped off, but the significant figures other than zeroes will remain preserved i.e- 2130.05 will remain 2130.05.
If you want to preserve the format pass it as a string. It will work.
Hope it helps..

Check to see if JavaScript value is a Decimal

I'm working on an app. I'm using JavaScript to save values to a database. My database table has a column that holds a Decimal value. It works fine with some old C# code. In fact, in C#, I'd do this:
decimal? myValue = null;
decimal temp = 0;
if (Decimal.TryParse(myString, out temp)) {
myValue = temp;
}
I understand that JavaScript only has a single Number type. However, because I'm saving my value to the database, how do I ensure that its a decimal? In C#, I know that a Float is basically a 32-bit value, a Double is basically a 64-bit value, and a Deciml is basically a 128-bit value. However, I'm not sure how to translate this to JavaScript.
Can anyone provide some insights?
Thanks!
You would check for decimals in javascript like this:
var dec = 3.14;
if(typeof dec == "number" && (dec+'').indexOf('.')!=-1){
var myvalue = dec;
}
Note that the above will fail on numbers such as 5.00 as noted by FelixKling as the decimals are lost when it is converted to String.

Large Decimal Number Parse

I know this has some answers but not exactly what I'm looking for.
I have an application with a custom scripting language for file formats where numbers can be added, subtracted, etc...
One part will produce decimal,hex conversion and I was able to use the BigInteger class which is nice because I don't have to worry about large values.
For math operations though I am stuck using a Decimal and I would like to know if anyone has any suggestions for something like BigInteger that I can use for Decimal. I have seen BigRational but it doesn't look like it will fit.
Here is the code snippet where it's used. The asdecimal probably looks stupid but it's just decimal parse where zero is returned if invalid.
private string Subtract(StringReader reader, string text)
{
string value = reader.ReadToEnd();
value = Evaluate(value);
var a = text.AsDecimal();
var b = value.AsDecimal();
return (a - b).ToString();
}
To make this more clear. This function can handle any conceivable situation because of BigInteger
private string HexToDec(string value)
{
try
{
var input = this.Evaluate(value);
var number = BigInteger.Parse(input, System.Globalization.NumberStyles.HexNumber);
return number.ToString();
}
catch (Exception)
{
return "INVALID_HEX_NUMBER";
}
}
I would like subtract tot be as flexible. If it's not possible, that is fine.

Formatting double as string in C#

I have a Double which could have a value from around 0.000001 to 1,000,000,000.000
I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:
String.Format("{0:.000000000}", number);
if it's not that small, say 0.001 then I want to use something like
String.Format("{0:.00000}", number);
and if it's over, say 1,000 then format it as:
String.Format("{0:.0}", number);
Is there a clever way to construct this format string based on the size of the value I'm going to format?
Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately.
string s;
double epislon = 0.0000001; // or however near zero you want to consider as zero
if (Math.Abs(value) < epislon) {
int digits = Math.Log10( Math.Abs( value ));
// if (digits >= 0) ++digits; // if you care about the exact number
if (digits < -5) {
s = string.Format( "{0:0.000000000}", value );
}
else if (digits < 0) {
s = string.Format( "{0:0.00000})", value );
}
else {
s = string.Format( "{0:#,###,###,##0.000}", value );
}
}
else {
s = "0";
}
Or construct it dynamically based on the number of digits.
Use the # character for optional positions in the string:
string.Format("{0:#,###,##0.000}", number);
I don't think you can control the number of decimal places like that as the precision of the double will likely mess things up.
To encapsulate the logic of deciding how many decimal places to output you could look at creating a custom formatter.
The first two String.Format in your question can be solved by automatically removing trailing zeros:
String.Format("{0:#,##0.########}", number);
And the last one you could solve by calling Math.Round(number,1) for values over 1000 and then use the same String.Format.
Something like:
String.Format("{0:#,##0.########}", number<1000 ? number : Math.Round(number,1));
Following up on OwenP's (and by "extension" tvanfosson):
If it's common enough, and you're on C# 3.0, I'd turn it into an extension method on the double:
class MyExtensions
{
public static string ToFormmatedString(this double d)
{
// Take d and implement tvanfosson's code
}
}
Now anywhere you have a double you can do:
double d = 1.005343;
string d_formatted = d.ToFormattedString();
If it were me, I'd write a custom wrapper class and put tvanfosson's code into its ToString method. That way you could still work with the double value, but you'd get the right string representation in just about all cases. It'd look something like this:
class FormattedDouble
{
public double Value { get; set; }
protected overrides void ToString()
{
// tvanfosson's code to produce the right string
}
}
Maybe it might be better to make it a struct, but I doubt it would make a big difference. You could use the class like this:
var myDouble = new FormattedDouble();
myDouble.Value = Math.Pi;
Console.WriteLine(myDouble);

Categories