0

Lets say I have shipping costs of 10.00 USD. If i pass this value to a float it will become 10. Not "10.00".

I tried:

float shippingRounded = float.Parse("10,00");

But this parses the string to a float and cuts the last two digits.

How can I use a float and still have it have two decimal places, irregardles of what they are?

innom
  • 770
  • 4
  • 19
  • 6
    You cannot; `float` does not record precision. For currency amounts you're looking for `decimal`. You can, of course, choose to always *format* a floating-point value with two decimals (`10f.ToString("N2")`) but you really don't want to be using floating-point for monetary values in any case. – Jeroen Mostert May 21 '21 at 10:59
  • If you want to format a float so it can be displayed as a string you can use [yourFloatVariable.ToString("0.00")](https://stackoverflow.com/questions/6356351/formatting-a-float-to-2-decimal-places). But as for it's actual value, it's a number it wont record superfluous values at the end of it such as 0's unless there's data that's important behind the zeros like a decimal point. – DekuDesu May 21 '21 at 11:01
  • To recover the digits you will need to format the number for display purposes. – phuzi May 21 '21 at 11:01
  • 2
    [Decimal](https://learn.microsoft.com/en-us/dotnet/api/system.decimal) is more appropriate type to store currency for many reasons, see [this topic](https://stackoverflow.com/q/618535/1997232). – Sinatr May 21 '21 at 11:13

2 Answers2

1

With:

 shippingRounded.ToString(".00")

It will display

10,00

  • Thank you, this is the clostest to what I needed. – innom May 21 '21 at 11:10
  • 1
    @innom Try using a different value than 10.xx, try 123456.xx and see what problems you will have if you keep using `float`. You **absolutely *should*** switch to `decimal`. – Lasse V. Karlsen May 21 '21 at 11:41
0

I wrote a function that will always convert a price into the correct format:

public static string ReturnFormattedPrice(string priceWithOutCurrencySymbol)
        {

            string[] values = new string[2];
            List<string> valueList = new List<string>();

            valueList.Add("");
            valueList.Add("");

            // cause it will be either dot or comma 
            if (priceWithOutCurrencySymbol.Contains(","))
                values = priceWithOutCurrencySymbol.Split(",");
            else
                values = priceWithOutCurrencySymbol.Split(".");

            valueList[0] = values[0];


            if (values.Length == 1)       
                valueList[1] = ",00";
            else if(values[1].Length == 1)
                valueList[1] = "," + values[1] + "0";
            else
                valueList[1] = "," + values[1];



            return valueList[0] + valueList[1];

        }
innom
  • 770
  • 4
  • 19