Java整数部分填充 [英] Java integer part padding
问题描述
2.11 - > 02.11
22.11 - > 22.11
222.11 - > 222.11
2.1111121 - > 02.1111121
double x = 2.11;
System.out.println(String.format(%08.5f,x));
可以做到这一点,但是这是烦人的正确的尾随零,我想有一个任意大的浮动
String.format(%02d%s,(int)x,String.valueOf(x-(int) x).substring(1))
是完全丑陋和不完整的(给出02.1099 ...) / p>
新的DecimalFormat(00。#############)。format(x)$
$ b 将截断浮动部分
更好的解决方案
解决方案
最好的我可以来的是
String [] p = s.split(\\\。);
if(2 == p.length){
return String.format(%02d。%s,Integer.parseInt(p [0]),p [1]);
}
return String.format(%02d,Integer.parseInt(p [0]));
$ pad $(String.valueOf(1.11111118)) - > 01.11111118
Sorry I was initially wanting to do it in php PHP integer part padding, but realised I will do it in Java in another part of code
So I need to format numbers with the integer part at least 2 chars
2.11 -> 02.11
22.11 -> 22.11
222.11 -> 222.11
2.1111121 -> 02.1111121
double x=2.11;
System.out.println(String.format("%08.5f", x));
could do it, but it's annoying the right trailing zeros, I would like to have an arbitrary large floating part
String.format("%02d%s", (int) x, String.valueOf(x-(int) x).substring(1))
is totally ugly and unexact (gives 02.1099...)
new DecimalFormat("00.#############").format(x)
will truncate floating part
thx for any better solutions
解决方案 the best I could come with is
public static String pad(String s){
String[] p = s.split("\\.");
if (2 == p.length){
return String.format("%02d.%s", Integer.parseInt(p[0]), p[1]);
}
return String.format("%02d", Integer.parseInt(p[0]));
}
pad(String.valueOf(1.11111118)) -> 01.11111118
这篇关于Java整数部分填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆