-2

I want my float to only display first 2 number behind the dot. I don't know how to search on google because my English is not that good but here is what I want in C#

float exampleFloat = 1.32232313F
Console.WriteLine(exampleFloat)

normally this would write in console 1.32232313F right? I want this number to be 1.32

Altanbagana
  • 41
  • 1
  • 9
  • 3
    Does this answer your question? [Leave only two decimal places after the dot](https://stackoverflow.com/questions/1291483/leave-only-two-decimal-places-after-the-dot) – TontonVelu Oct 22 '20 at 07:50

2 Answers2

1

I know this is a joke... I am new here and I wanna help and be helped so.

here is the answer.

for writing to console with just the formatting

    float exampleFloat = 1.32232313F;
    Console.WriteLine(exampleFloat.ToString("0.00"));

if you wanna just round them in the variable as is.

    Math.Round(exampleFloat,2); 

to save the variable that way so if you wanna perform further operations.

-3

Like this:

Round a float value to 2 decimal places in C#

float f = 10.123456F;
float fc = (float)Math.Round(f, 2);

Output : 10.12

AntonioSk
  • 528
  • 3
  • 20
  • What's wrong with `Math.Round(f, 2)`? – InBetween Oct 22 '20 at 07:59
  • I have editted it thanks for the tip! – AntonioSk Oct 22 '20 at 08:00
  • I am writing this on Unity and it says The name 'Math' does not exist in the current context – Altanbagana Oct 22 '20 at 08:01
  • the previous one worked tho xD – Altanbagana Oct 22 '20 at 08:04
  • 3
    Since a `float` cannot accurately store a number like this, rounding to two is at best hoping for whatever is going to display it agrees with the truncation/rounding. It's better to (instead, or additionally) consider where the two digits are needed, such as when displaying as text, and then using formatting rules then to limit it. – Lasse V. Karlsen Oct 22 '20 at 08:08
  • If your issue is with the display of data, then change how the data is displayed. Don't modify the data unless the data actually needs to be modified. – Immersive Oct 22 '20 at 13:21