如何在Java中将电话号码格式化为字符串? [英] How do format a phone number as a String in Java?

查看:1070
本文介绍了如何在Java中将电话号码格式化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直存储电话号码,我想在将电话号码打印成字符串时添加连字符。

I have been storing phone numbers as longs and I would like to simply add hyphens when printing the phone number as a string.

我尝试使用 DecimalFormat 但不喜欢连字符。可能是因为它用于格式化十进制数而不是长数。

I tried using DecimalFormat but that doesn't like the hyphen. Probably because it is meant for formatting decimal numbers and not longs.

long phoneFmt = 123456789L;
DecimalFormat phoneFmt = new DecimalFormat("###-###-####");
System.out.println(phoneFmt.format(phoneNum)); //doesn't work as I had hoped

理想情况下,我想在该区域有括号代码也是。

Ideally, I would like to have parenthesis on the area code too.

new DecimalFormat("(###)-###-####");

这样做的正确方法是什么?

What is the correct way to do this?

推荐答案

这就是我最终做到的方式:

This is how I ended up doing it:

private String printPhone(Long phoneNum) {
    StringBuilder sb = new StringBuilder(15);
    StringBuilder temp = new StringBuilder(phoneNum.toString());

    while (temp.length() < 10)
        temp.insert(0, "0");

    char[] chars = temp.toString().toCharArray();

    sb.append("(");
    for (int i = 0; i < chars.length; i++) {
        if (i == 3)
            sb.append(") ");
        else if (i == 6)
            sb.append("-");
        sb.append(chars[i]);
    }

    return sb.toString();
}

我知道这不支持国际号码,但我不写一个真正的应用程序,所以我不关心这一点。我只接受10个字符长的电话号码。我只是想用一些格式打印它。

I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that. I only accept a 10 character long as a phone number. I just wanted to print it with some formatting.

感谢您的回复。

这篇关于如何在Java中将电话号码格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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