将带有点或逗号的字符串转换为浮点数 [英] Convert String with Dot or Comma to Float Number
问题描述
我总是喜欢在我的函数中输入数字,范围从0.1到999.9(小数部分总是用'。'分隔,如果没有小数,那么没有'。',例如9或7。 / p>
如何将此String转换为浮点值而不管本地化(某些国家/地区使用','来分隔数字的小数部分。我总是用'。'来获取它。) ?这取决于本地计算机设置吗?
Float.parseFloat()
方法不依赖于区域设置。它需要一个点作为小数分隔符。如果输入中的小数分隔符始终为点,则可以安全地使用它。
NumberFormat
类提供了区域设置感知的解析和格式,如果您需要适应不同的区域设置。
I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .
How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the '.')? Does this depend on local computer settings?
The Float.parseFloat()
method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.
The NumberFormat
class provides locale-aware parse and format should you need to adapt for different locales.
这篇关于将带有点或逗号的字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!