Skip to content

Instantly share code, notes, and snippets.

@froop
Created October 5, 2011 01:25
Show Gist options
  • Save froop/1263384 to your computer and use it in GitHub Desktop.
Save froop/1263384 to your computer and use it in GitHub Desktop.
[Java] 全角の数字・小数点記号・マイナス記号を半角に変換
public static String toHankakuNum(String text) {
StringBuilder res = new StringBuilder();
final String listZens = "0123456789.-";
final String listHans = "0123456789.-";
for (int textIdx = 0; textIdx < text.length(); textIdx++) {
char ch = text.charAt(textIdx);
int listIdx = listZens.indexOf(ch);
if (listIdx >= 0) {
res.append(listHans.charAt(listIdx));
} else {
res.append(ch);
}
}
return res.toString();
}
@Test
public void testToHankakuNum() {
assertEquals("", Utilities.toHankakuNum(""));
assertEquals("1", Utilities.toHankakuNum("1"));
assertEquals("a", Utilities.toHankakuNum("a"));
assertEquals("あ", Utilities.toHankakuNum("あ"));
assertEquals("-123456789.0", Utilities.toHankakuNum("-123456789.0"));
assertEquals("11aあ22", Utilities.toHankakuNum("11aあ22"));
}
@zhmz1326
Copy link

zhmz1326 commented Aug 4, 2015

It was a great help! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment