1

I have an overloaded extension method which rounds either a decimal or double to N number of decimal places and it works perfectly.

public static class NumberExtensions
{
    public static string ToStringNDecimalPlaces(this double dbValue, int nDecimal)
    {
        return dbValue.ToString("N" + nDecimal);
    }

    public static string ToStringNDecimalPlaces(this decimal dbValue, int nDecimal)
    {
        return dbValue.ToString("N" + nDecimal);
    }
}

My question is, I want to create another called something like, "ToStringFirstDecimalPlace" or something like that which takes the decimal value and rounds it to the first logical decimal value after the 0s. Let me give some, this is how I would like the method to work:

e.g.

  • 0.000345879 = 0.0003
  • 0.019356 = 0.02
  • 0.1 = 0.1

So it ignores the leading 0s and takes the nth to be the first logical number that makes sense instead of just rounding to 0.0 for example.

cullimorer
  • 755
  • 1
  • 5
  • 23

3 Answers3

0

Well can't you count the number of zeroes and then format accordingly?

Example for positive values:

string result;
if(dbValue != 0)
{
    int count = 0;
    var copyDb = dbValue;
    while(copyDb < 1)
    {
        copyDb *= 10;
        count++;
    }
    result = dbValue.ToStringNDecimalPlaces(count);
}
else
{
    result = "0";
}
Rafalon
  • 4,450
  • 2
  • 16
  • 30
  • If the value is -5.049 for example, you're going to make the `result = "0"`, that's incorrect. – Youssef13 May 27 '20 at 11:14
  • Yeah, that would need to be tweak a little (`Math.Abs`) for negative values, but OP only provided positive values as examples – Rafalon May 27 '20 at 11:15
0

You can write the following function to achieve this:

public static string ToStringNDecimalPlacesIgnoreZeros(this double dbValue)
{

    var value = dbValue - Math.Floor(dbValue); // Get rid of integer digits
    int position = 0;
    while (value > 0 && Math.Floor(value) == 0)
    {
        value = value * 10;
        position += 1;
    }

    if (value == 0)
        return dbValue.ToString("N");
    else
        return dbValue.ToStringNDecimalPlaces( position);
}
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

First, assume that the input is between 0 and 1, inclusive. If not, subtract the integer part (and if negative, negate the remainder) before rounding the rest (this process can be reversed after the rounding is complete). Then, do something like this:

RountToFirstLogical(input)
1. place = 1
2. while place > input
3.    place = place / 10
4. input = round(input/place) * place
5. return input

Examples:

input=0.000345879
place=1, 0.1, 0.01, 0.001, 0.0001
input/place = 3.45879
round(input/place) = 3
round(input/place) * place = 0.0003

input=0.019356
place=1, 0.1, 0.01
input/place = 1.9356
round(input/place) = 2
round(input/place)*place = 0.02

input=0.1
place=1, 0.1
input/place=1
round(input/place)=1
round(input/place)*place=0.1
Patrick87
  • 27,682
  • 3
  • 38
  • 73