如何从浮点变量值中获取2位小数值而不舍入浮点值。 [英] How to get 2 decimal place value from a float variable value with out rounding the float value.
问题描述
假设我有一个浮点数。喜欢
float f = 123.4563434;
现在我希望float变量的值为2十进制像...一样的价值。
f = 123.45。
i想要精确的2位小数值而没有四舍五入。
如何转换123.4563434到123.45。
实际上我必须计算出准确的值。所以我在小数点后只需要2位小数。
如何实现这个?
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 ?
推荐答案
你可以这样做:
You can do this:
float f = 123.4563434;
float truncatedToTwoDigits = Math.Truncate(f * 100) / 100;
将 f
乘以100后,得到 12345.63434
。如果你截断小数点后的所有内容(这就是Math.Truncate的作用),你得到 12345
。除以100,你得到 123.45
,这是你想要的结果。
你可以做到这一点对于小数点后的任何 n 位,然后乘以除以 10 n 而不是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.
您可以尝试乘以100,截断为整数值,然后除以100:
You can try to multiply by 100, truncating to integer value, and then divide-back by 100:
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.
请注意,您在小数位后显示七位数的测试值;对于浮动/单个,你将至少丢失该数字的最后一位数,因为你超过了该格式的精确能力;请参阅:[ ^ ]和[< a href =http://stackoverflow.com/a/21688396/133321target =_ blanktitle =New Window> ^ ]。
对于种类:
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:
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
这篇关于如何从浮点变量值中获取2位小数值而不舍入浮点值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!