【问题标题】:Celsius to fahrenheit android摄氏到华氏安卓
【发布时间】:2013-04-17 11:49:49
【问题描述】:
public static int convertCelsiusToFahrenheit(Long celcious){
    return Math.round(celcious * 9/5 + 32);     
}

我正在尝试将其设置为我的 TextField。我无法在Text Field 中设置值,因为我得到了 NumberFormatException。 我怎样才能用精度值发送它。

holder.textItem.setText(convertCelsiusToFahrenheit(Long.parseLong(
              custom.getTemperature())));

java.lang.NumberFormatException:无效长:“32.2222222222222”

【问题讨论】:

  • 看来你需要Doubledouble 这里。
  • Long 是整数类型,所以"32.2222" 无效。

标签: java android


【解决方案1】:

float 转换为long

你可以只使用强制转换

(long) custom.getTemperature()

但是,如果您只有一个表示浮点数的字符串,您可能需要更改转换函数,改为接收浮点数。-

public static int convertCelsiusToFahrenheit(float celcious){
    return Math.round(celcious * 9.0f / 5.0f + 32);     
}

然后通过

Float.parseFloat(custom.getTemperature())

不要忘记除以9.0f / 5.0f 而不是9 / 5,因为最后一个是整数除法,并且总是返回 1。

【讨论】:

  • 请注意,“Long.parseLong”用于将 String 转换为 Long 并且您不能使用 (long)String 将 String 转换为 long
【解决方案2】:

试试这个,

 holder.textItem.setText(" "+convertCelsiusToFahrenheit(Float.parseFloat(
                  custom.getTemperature())));

public static int convertCelsiusToFahrenheit(Float celcious){
            return Math.round(celcious * 9/5 + 32);     
        }

【讨论】:

  • 阿伦:我收到了这个错误。 04-17 17:51:08.901: E/AndroidRuntime(1087): android.content.res.Resources$NotFoundException: 字符串资源 ID #0x5a 04-17 17:51:08.901: E/AndroidRuntime(1087): 在 android。 content.res.Resources.getText(Resources.java:229) 04-17 17:51:08.901: E/AndroidRuntime(1087): 在 android.widget.TextView.setText(TextView.java:3620)
  • 确保将字符串资源分配给在 values 文件夹中正确声明的视图
  • 我的想法是如何将 int 类型设置到 TextField 中。
  • 看我的回答,你需要将返回的int格式化为string
【解决方案3】:

除了关于解析为float 等的答案之外,请注意setText 已重载。当它需要一个 int 时,它是一个资源 Id,所以创建一个 string 并给它:

代替:

holder.textItem.setText(convertCelsiusToFahrenheit(...));

做:

holder.textItem.setText(String.format("%d", convertCelsiusToFahrenheit(...)));

或者:

holder.textItem.setText(String.format("%d\x00B0 f", convertCelsiusToFahrenheit(...)));

应该给你“10° f”(未经测试)

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2017-11-30
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多