Java android中的Float到String的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19900402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Float to String conversion in android
提问by pitu
i am trying simple calculation of float value but the output are not proper
我正在尝试简单计算浮点值,但输出不正确
Log.i("100/50", Float.toString(100/50));
Log.i("100/100", Float.toString(100/100));
Log.i("100/250", Float.toString(100/250));
Log.i("1/5", Float.toString(1/5));
logcat output
logcat 输出
11-10 23:36:23.677: I/100/50(28562): 2.0
11-10 23:36:23.677: I/100/100(28562): 1.0
11-10 23:36:23.685: I/100/250(28562): 0.0
11-10 23:38:23.685: I/1/5(28562): 0.0
its a simple calculation of float, why its displaying such answer
它是一个简单的浮点计算,为什么它显示这样的答案
采纳答案by Evgeniy Dorofeev
You need to use floats instead of ints, try Log.i("100/50", Float.toString(100f/50));
this makes Java to use float arithmetic, otherwise it does int division then converts the result to float
您需要使用浮点数而不是整数,试试Log.i("100/50", Float.toString(100f/50));
这让 Java 使用浮点运算,否则它会进行整数除法,然后将结果转换为浮点数
回答by Ahmad Raza
Use this code.
使用此代码。
Log.i("100/50", Float.toString(100/50f)); Log.i("100/100", Float.toString(100/100f)); Log.i("100/250", Float.toString(100/250f)); Log.i("1/5", Float.toString(1/5f));
Log.i("100/50", Float.toString(100/50f)); Log.i("100/100", Float.toString(100/100f)); Log.i("100/250", Float.toString(100/250f)); Log.i("1/5", Float.toString(1/5f));
Hope it will work for you.
希望它对你有用。
回答by Jitender Dev
Do like this
这样做
Log.i("100/250", Float.toString(100f/250f));
Log.i("1/5", Float.toString(1f/5f));
output is
输出是
11-11 12:25:32.198: I/100/250(351): 0.4
11-11 12:25:32.208: I/1/5(351): 0.2
Float.toString takes an input floating point
Float.toString 接受一个输入浮点数
public static String toString (float f)
where f is the float to convert to a string.
More information is available on Developers Website.
开发人员网站上提供了更多信息。
回答by Sunil Kumar Sahoo
you are performing division of two integers. so by default output will be in integer. Instead of that try to type case the dividend into float eg (float)100/250 so the out put will be in float and you will get proper result
您正在执行两个整数的除法。所以默认情况下输出将为整数。而不是尝试将情况下的股息输入浮动,例如 (float)100/250 这样输出将处于浮动状态,您将获得正确的结果
eg instead of 100/250 try (float)100/250 or 100f/250
例如,而不是 100/250 try (float)100/250 或 100f/250