0

Could someone please help me with this. I'm trying to replace the Value with the same value but only with the first decimal. As you can see below i end up with the same result as I start with.

public class QoutaDataHolder
{
  public double StartTime { get; set; }

  public double EndTime { get; set; }

  public double Value { get; set; }

  public string QoutaRuleID { get; set; }
}

List<QoutaDataHolder> correctionQoutas

for (int i = 0; i < correctionQoutas.Count; i++)
{
  if (correctionQoutas[i].Value % 1 != 0) //Value = 2.88888889
  {
    var trunkatedValue = Math.Truncate(correctionQoutas[i].Value*10); //28
    double newValue = trunkatedValue/10; // Back to 2.88888889!?!?
    correctionQoutas[i].Value = newValue; // Want to assign 2.8
  }
}

EDIT: I don't want to round the value!

Andy
  • 503
  • 3
  • 15
  • 29
  • use ``Math.Round`` – Ehsan Sajjad May 10 '16 at 12:10
  • Edited my post, I don't want to round the value. – Andy May 10 '16 at 12:12
  • can you tell what's preventing you to use that? – Ehsan Sajjad May 10 '16 at 12:13
  • I always want the first decimal, undependant of what the second decimal is. – Andy May 10 '16 at 12:16
  • 1
    [http://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding](http://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding) – Jason Evans May 10 '16 at 12:18
  • 1
    I cannot duplicate this. The result of `newValue` is `2.8` –  May 10 '16 at 12:19
  • I'm not sure floating point numbers are a good fit if the exact decimal fraction is important (e.g. this is money). You should probably consider using `decimal` instead - see [this question](http://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when) – Charles Mager May 10 '16 at 12:22

3 Answers3

0

Ehsan Sajjad is right. You need to use Math.Round with second parameter as 1.

for (int i = 0; i < correctionQoutas.Count; i++)
{
  if (correctionQoutas[i].Value % 1 != 0) //Value = 2.88888889
  {
    correctionQoutas[i].Value = math.Round(correctionQoutas[i].Value, 1); // Want to assign 2.8
  }
}
Chaos Legion
  • 2,730
  • 1
  • 15
  • 14
0

Here is a solution specific to your question: Just use conversions to get the values

for (int i = 0; i < correctionQoutas.Count; i++)
{
    if (correctionQoutas[i].Value % 1 != 0) //Value = 2.88888889
    {
        var trunkatedValue = (int)(correctionQoutas[i].Value * 10); //28
        double newValue = (double)trunkatedValue / 10; // not back to 2.88888889 anymore
        correctionQoutas[i].Value = newValue;
    }
}
Marcel B
  • 508
  • 2
  • 9
-1

You could do:

var trunkatedValue = Math.Floor(correctionQoutas[i].Value*10); //28
Jonathan Nappee
  • 430
  • 2
  • 11