本文介绍了在Java中显示前导零(0)的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我必须添加两个整数,一个是0001而另一个是0002.如果我在java中添加它然后我得到3然而我想要0003.我是否必须制作一个循环来映射零或者是否存在更方便。
Say that I have to add two integers one being 0001 and the other 0002. If I add it in java then I get 3 however I would like 0003. Would I have to make a loop to map out the zeros or is there an easier way.
推荐答案
不要将数字与字符串表示的数字混淆。你的问题围绕后者 - 如何将数字表示为带前导零的字符串,并且有几种可能的解决方案,包括使用DecimalFormat对象或String.format(...)。
Don't confuse numbers with String representation of numbers. Your question revolves around the latter -- how to represent a number as a String with leading zeros, and there are several possible solutions including using a DecimalFormat object or String.format(...).
ie,
int myInt = 5;
String myStringRepOfInt = String.format("%05d", myInt);
System.out.println("Using String.format: " + myStringRepOfInt);
DecimalFormat decimalFormat = new DecimalFormat("00000");
System.out.println("Using DecimalFormat: " + decimalFormat.format(myInt));
这篇关于在Java中显示前导零(0)的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!