表示电话号码的正确方法是什么? [英] What's the right way to represent phone numbers?

查看:278
本文介绍了表示电话号码的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在我的某个应用程序中代表手机号码。

I'm having trouble representing a mobile number in one of my applications.

我想知道是否有一个Integer类允许你存储这样的从0417254482开始的数字。也许使用字符串更合适?
目前,当我尝试使用代表一个带有整数的电话号码时,双打多头我似乎存储随机数而不是我打算存储的数字。

I was wondering if there is an Integer class that will allow you to store such a number starting with 0417254482. Perhaps using a string be a more appropriate? At present when I'm trying to use represent a phone number with ints, doubles longs I seem to store random numbers and not the numbers I meant to store.

推荐答案

使用字符串。除了其他任何东西,如果你使用整数,你将无法存储前导零。您肯定不应该使用 int (太小) float double (数据丢失的风险太大 - 见下文); long BigInteger 可能是合适的(除了领先的零问题),但坦率地说我会选择字符串。这样你就可以存储用户输入的任何破折号或空格,以便更容易记住号码,如果你愿意的话。

Use String. Aside from anything else, you won't be able to store leading zeroes if you use integers. You definitely shouldn't use int (too small) float or double (too much risk of data loss - see below); long or BigInteger could be appropriate (aside from the leading zeroes problem), but frankly I'd go with String. That way you can also store whatever dashes or spaces the user has entered to make it easier to remember the number, if you want to.

就上面提到的 float double - float 绝对没有足够的精度; double 可以工作如果你很高兴你永远不会需要超过16位数(比你的<$ c $少) c> long )但是你需要非常小心地将值从 double 转换回 string ,你得到了确切的值。许多格式转换会为您提供一个近似值,可能精确到10位有效数字 - 但您需要一个精确的整数。基本上,使用浮点电话号码是一个根本不好的主意。如果 使用固定宽度的数字类型,请使用 long ,但理想情况下,请完全避免使用。

In terms of the "data loss" mentioned above for float and double - float definitely doesn't have enough precision; double could work if you're happy that you'll never need more than 16 digits (a couple fewer than you get with long) but you would need to be very, very careful that anywhere you convert the value back from double to string, you got the exact value. Many formatting conversions will give you an approximation which may be accurate to, say, 10 significant digits - but you'd want an exact integer. Basically, using floating point for phone numbers is a fundamentally bad idea. If you have to use a fixed-width numeric type, use a long, but ideally, avoid it entirely.

这篇关于表示电话号码的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆