6

I'm using c#, every time i insert 3 decimal places, the number gets rounded e.g.

1.538

rounds

to 1.54

I want the number to be as is e.g. 1.53 (to two decimal places only without any roundings).

How can i do it?

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
user311509
  • 2,856
  • 12
  • 52
  • 69
  • 6
    It's difficult to answer your question without more information. Where are you "inserting" the decimal places and how are you printing it? Most probably, the number is stored correctly but the way you are printing it, only 2 decimal places are showing up. – casablanca Jul 02 '10 at 17:24
  • 2
    Math.Truncate() could possibly help you here, but we need more information. – CrimsonX Jul 02 '10 at 17:26
  • 2
    This definitely needs more information, like say the snippet of code which is producing the results listed. – Nick Larsen Jul 02 '10 at 17:27
  • 1
    Please use technical, descriptive terms when asking a question. – mqp Jul 02 '10 at 17:28
  • 1
    In this case, the user is likely new to programming and is trying to describe the problem in as technical terms as he can at his skill level. Though perhaps he can describe the context of the problem a bit better. – Armstrongest Jul 02 '10 at 17:36

2 Answers2

7

I believe you want to use Math.Truncate()

float number = 1.538
number = Math.Truncate(number * 100) / 100;

Truncate will lop off the end bit. However, bear in mind to be careful with negative numbers.

It depends on whether you always want to round towards 0, or just lop off the end, Math.Floor will always round down towards negative infinity. Here's a post on the difference between the two.

Community
  • 1
  • 1
Armstrongest
  • 15,181
  • 13
  • 67
  • 106
3

Found this link which gives a good code snippet to allow you to specify the number decimals places you want like Math.Round() allows.

Basically it's this:-

public static double Floor(this double d, int decimals) {
    return Math.Floor(d * Math.Pow(10, decimals)) / Math.Pow(10, decimals);
}
Andy Robinson
  • 7,309
  • 2
  • 30
  • 20