Click here to Skip to main content
15,891,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose i have a float number. like

float f=123.4563434;

now i want the value of the float variable with 2 decimal place value like.

f=123.45.

i want the exact 2 decimal place value with out the rounding.

how to convert from 123.4563434 to 123.45.

actually i have to calculate the accurate value. so i need only 2 decimal place after the decimal point.

how to achive this ?
Posted
Comments
Sinisa Hajnal 14-Dec-15 11:03am    
Just to clarify: you want to show 123.45, and your f value should have full precision. OR you want your f variable to contain 123.45, but without using rounding. If it is this later option, why? What is wrong with rounding?

If it is the first one, just call f.ToString("N2");
CHill60 14-Dec-15 11:08am    
That only displays the value (and it rounds it to 123.46)
Sinisa Hajnal 14-Dec-15 11:09am    
I was just asking for clarification - avoiding the rounding sounds like it's a display problem.
Mahesh Pattnayak 14-Dec-15 11:51am    
no sir , i don't need rounding.

i want the accurate value for calculation
like 123.456789 - i need only 123.45
Sinisa Hajnal 14-Dec-15 12:01pm    
But this is NOT accurate value. Accurate value has 7 decimals (as your example shows). Anyhow, you have two good solutions now.
Check the documentation for Math.Round there are several options for rounding toward / away from zero as well as "standard" rounding. Good luck.

You can do this:
C#
float f = 123.4563434;
float truncatedToTwoDigits = Math.Truncate(f * 100) / 100;

After multiplying f by 100, you get 12345.63434. If you truncate everything after the decimal point (that's what Math.Truncate does), you get 12345. By dividing that by 100, you get 123.45, which is the result you desired.

You can do this for any n digits after the decimal point, then just multiply and divide by 10n instead of 100.
 
Share this answer
 
v2
Comments
phil.o 14-Dec-15 11:07am    
Dammit, you beat me :)
5'd
You can try to multiply by 100, truncating to integer value, and then divide-back by 100:
C#
float f = 123.4563434f;
float temp = Math.Floor(f * 100f); // temp = 12345
float result = temp / 100f; // result = 123.45

public static float TrucatedValue(this float value) {
   return Math.Floor(value * 100f) / 100f;
}

I included an extension method that you can use on float values to get the truncated value.
Hope this helps.
 
Share this answer
 
Note that you show a test value with seven digits after the decimal place; for a float/single, you are going to "lose" at least the last digit of that number, since you exceed that format's precision capability; see: [^], and [^].

For variety:
C#
private float? FloatToNPlaces(int nplaces, float f)
{
    string f1 = f.ToString("n7");
    int i = f1.IndexOf('.');
    nplaces++;

    if (i < 0 || f1.Substring(i).Length < nplaces) return null;

    return Convert.ToSingle(f1.Substring(0, f1.IndexOf('.') + nplaces));
}

// usage:
// float fx? = FloatToNPlaces(3, 4563434F); // 123.45
// float fx? = FloatToNPlaces(0, 123.4563434F); // 123.0
// float fx? = FloatToNPlaces(2, 123.0F); // 123.0

// float fx? = FloatToNPlaces(5, 123.4563434F); // null because of float limitations as described above
 
Share this answer
 
v4
Comments
Richard Deeming 14-Dec-15 14:19pm    
Sorry, I've got to down-vote that. Converting to a string just to truncate the number - particularly as your Substring call could fail if the number has less than three decimal places - is a particularly bad approach. The other two solutions are the correct way to do this.
BillWoodruff 14-Dec-15 14:45pm    
"your Substring call could fail if the number has less than three decimal places"

Incorrect.

Hi Richard, I always respect your judgement, but note the use of a float? result here which prevents the most common error: an "overshoot."

The current code (revised perhaps since you first looked at it ?) avoids the error you mention:

float? fx = FloatToTwoPlaces(2, 123.0f);

now returns 123.0. I'll correct the usage example to show this.

And, also note:

float? fx = FloatToTwoPlaces(2, 123.4f);

will return 123.4f as expected

While you may not like this technique, I don't think a post like this adding an additional way of dealing with the problem merits a down-vote ... particularly since it seems you did not fully understood the code.
Richard Deeming 14-Dec-15 14:52pm    
Well, you've changed your answer since my comment so that it no longer throws an exception if there aren't enough decimal places.

I have to disagree with the way the method now works. If you want to round 120.0f to two decimal places, null is not the obvious result.

FloatToTwoPlaces(2, 123.4f) returns null, not 123.1f (or 123.4f, which I suspect you meant to write).

And you're still converting a number to a string, manipulating the string, and then converting back to a number. That's going to be horrendously inefficient compared to the other two solutions.
BillWoodruff 14-Dec-15 15:02pm    
Hi Richard, I caught the missing piece here, a missing argument "n7" in the f.ToString() call in the method; that accounts for the results you have complained about.

"And you're still converting a number to a string, manipulating the string, and then converting back to a number. That's going to be horrendously inefficient compared to the other two solutions."

I never claimed that I was doing anything but adding an alternative approach; sorry if that pushes your buttons :)
Richard Deeming 14-Dec-15 14:57pm    
If you really want to go down the number -> string -> number approach, all you need is:

string f1 = f.ToString("F" + nplaces);
return Convert.ToSingle(f1);


The Fixed-Point ("F") Format Specifier[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900