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

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

问题描述

我在我的一个应用程序中无法表示手机号码.

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.

推荐答案

使用 String.除此之外,如果您使用整数,您将无法存储前导零.您绝对不应该使用 int(太小)floatdouble(数据丢失风险太大 -见下文);longBigInteger 可能是合适的(除了前导零问题),但坦率地说,我会选择 String.这样,如果您愿意,您还可以存储用户输入的任何破折号或空格,以便更轻松地记住数字.

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.

floatdouble 上面提到的数据丢失"而言——float 肯定没有足够的精度;double 可能如果你很高兴你永远不需要超过 16 位的数字(比你使用 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天全站免登陆