Samra
Samra

Reputation: 2015

convert float to string preserving decimals

My float is 100.0 when i convert it to string it becomes 100.

rmt.MinNumber = 0.0;
rmt.MaxNumber = 100.0;

rmt.MaxLength = rmt.MinNumber.ToString() + " - " + rmt.MaxNumber.ToString();

I know I can do

rmt.MinNumber.ToString("0.0");

but that is also a setting saved in rmt.Decimal so

if rmt.Decimal = 1 then rmt.MaxLength = 100.0

if rmt.Decimal = 2 then rmt.MaxLength = 100.00 and so on...

How can i convert it to string preserving its decimal value

UPDATE

As suggested by CodeFuller

public static class Helper
{
   public static string Format(this float f, int n)
    {
        return f.ToString($"0.{new String('0', n)}");
    }
}

but currently it is giving me error ) expected

Upvotes: 0

Views: 257

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

You could still use ToString("0.0") method but you should build format specifier at run time since number of digits after the dot will vary.

Consider using following extension method:

public static class FloatExtensions
{
    public static string Format(this float f, int n)
    {
        // return f.ToString($"0.{new String('0', n)}");
        return f.ToString("0." + new String('0', n));
    }
}

rmt.MaxLength = rmt.MinNumber.Format(rmt.Decimal)

Upvotes: 1

Related Questions