Home > Blockchain >  C# Round and Convert to units
C# Round and Convert to units

Time:05-20

My function doesn't work as I expect..

        static string FormatWeight(double value)
        {
            if (value > 10000000) return (value / 10000000D).ToString("0.#### t");
            if (value > 100000) return (value / 100000D).ToString("0.#### kg");
            if (value > 1000) return (value / 1000D).ToString("0.#### g");
            return value.ToString("0.#### mg");
        }

Value given - Comes from database - is 13190.1(KG) it does display as mg where it should display as rounded value to tons (14.5T). How can we fix issue? Hope my question is understandable.

CodePudding user response:

Your function's base unit is in mg and you receive kg from the database. You need to change your function to have it's base unit as kg.

static string FormatWeightKg(double value)
    {
        if (value > 1000) return (value / 1000D).ToString("0.#### t");
        if (value > 1) return value.ToString("0.#### kg");
        if (value >= 0.0001) return (value*1000D).ToString("0.#### g");
        return (value*1000000D).ToString("0.#### mg");
    }
  • Related