1

So I'm going to be creating an app using realmdb - realm does not support decimal data types as of yet so I have been looking for an equivalent. If you could imagine object 1 returns 50, object 2 returns 50 & object 3 returns 12 = 112 but after 30% it should return £78.40 - Right now its returning £78.4

Below is my current code.

        Console.WriteLine("Object Costs");
        float ObjectOne = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 2 Costs");
        float ObjectTwo = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Object 3 Costs");
        float ObjectThree = Convert.ToInt32(Console.ReadLine());

        float Total = ObjectOne + ObjectTwo + ObjectThree;


        Console.WriteLine("Total: " + NewLine + "£" + Total);

        Console.WriteLine("DISCOUNTED - 30% OFF!!!");



        Console.WriteLine(NewLine + "Final Total: " + "£" + (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)));
bgcode
  • 101
  • 15
  • Does this answer your question? [How to format string to money](https://stackoverflow.com/questions/10615405/how-to-format-string-to-money) – Diado Feb 18 '20 at 10:56
  • You should look into string formatting in C#, for example: `yourfloat.ToString("0.00")` – Innat3 Feb 18 '20 at 10:56
  • if realmdb does not have decimal then I think it could be better to save as integers reprecenting cent or something but keep code as decimal. Using float for currencies gives a lot of problems. – Thomas Koelle Feb 18 '20 at 10:58
  • @Innat3 Silly question - how could I do calculations with that number at a later point though if Its a string object or would I just need to state Im converting it back before doing the sum? – bgcode Feb 18 '20 at 11:04
  • @BlairGibson you just use `.ToString()` to display the number as a string in the desired format. You can just keep making operations with the original float, and use `.ToString()` whenever you need to display it again – Innat3 Feb 18 '20 at 11:12
  • @BlairGibson, whenever you want to display number in particular format use `.ToString()`. This will format your number and will keep number it's original type. I would also request you to use decimal datatype when you are working with money. I added reason and documentation for it in my answer – Prasad Telkikar Feb 18 '20 at 11:16

1 Answers1

3

You can format your float value using ToString("0.00");

var discountedRate = (Total - Math.Round((Total / 100 * 30), 2, MidpointRounding.AwayFromZero)).ToString("0.00");

Console.WriteLine($"Final Total:£ {discountedRate}");

Try it online


Just a note: If you are dealing with money then use decimal instead of float

From MSDN:

The decimal type has more precision and a smaller range than both float and double, it's appropriate for financial and monetary calculations.

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44