-3

This i what I am trying to achieve:

If a float has more than 4 decimal places, only keep until the first 4 dec places (do not round.)

Eg.: 111.3547698 -> 111.3547

If a float has less than 4 decimals, leave unchanged

I came across this command:

float example = 111.3547698;

((Math.Truncate(Example * 1000)) / 1000)

But I do not want to round. According to the command posted above, 111.3547698 -> 111.354

but I need it to stay: 111.3547

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
SRT
  • 7
  • 1
  • 1

2 Answers2

4

One way to force this sort of truncating is to subtract a small amount so that Math.Round works as desired.

Math.Round(111.3547698 - 0.00005, 4)

is equivalent to

Math.Round(111.3547198, 4)

which does give you the 111.3547 that you're looking for.

The general case would be

Math.Round(num - 0.5/(Math.Pow(10, digits)), digits)

Where digits > 0

See https://codereview.stackexchange.com/questions/51951/truncate-decimal-places for a similar question/answer.

Community
  • 1
  • 1
Steve Desmond
  • 541
  • 5
  • 15
  • This works only for this case, but what is the value is different, this is just the example with a hard coded value, but if i want to truncate for different values, how do i do that? – SRT Mar 12 '15 at 21:43
  • added a general case to the solution above – Steve Desmond Mar 13 '15 at 00:29
0

Your code don't even compile in last vertion of C#.

It says:

Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type

That mean you should read about literals in C#

This peace of code that you probably copy from here have literal m that says to compiler this number will be decimal. If you want to work with float with same peace of code and truncate 4 digits you should use f literal and write like this:

float ex = 111.3547698f;
var ex4 = (Math.Truncate(ex * 10000f)) / 10000f;
Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • i tried with 10000f)) / 10000f, that is rounding off to three digits and giving the output as 111.355 – SRT Mar 12 '15 at 21:45
  • = ((Math.Truncate(XXXXXX.VALUE * 10000f)) / 10000f) -- 111.3547698 (Actual Value) ----- 111.355 (Return value) – SRT Mar 12 '15 at 21:52
  • XXXValue = ((Math.Truncate(xxxValueObj.VALUE * 10000f)) / 10000f). Where as i am trying to truncate the values which this XXXValue gives as output to 4 decimal places – SRT Mar 12 '15 at 22:05