PHP整数部分填充 [英] PHP integer part padding

查看:160
本文介绍了PHP整数部分填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用0填充整数部分,整数部分必须至少有2个字符

  str_pad(2, 2,0,STR_PAD_LEFT); // 02  - > works 
str_pad(22,2,0,STR_PAD_LEFT); // 22 - > works
str_pad(222,2,0,STR_PAD_LEFT); // 222-> works
str_pad(2.,2,0,STR_PAD_LEFT); // 2. - >失败 - > 02.或02
str_pad(2.11,2,0,STR_PAD_LEFT); // 2.11->失败 - > 02.11

有简单的代码吗?

<如果可能的话,请在Java中使用相同的语句。

  double x = 2.11; 
String.format(%02d%s,(int)x,String.valueOf(x-(int)x).substring(1))
pre>

不仅丑陋,而且为Java打印02.10999999999999988

edit :< Java的整数部分填充

解决你也可以使用 printf()函数填充整数:



键盘):

  
function pad($ n){
$ n = explode('。',(string)$ n);

if(2 === count($ n)){
return sprintf(%02d。%d \ n,$ n [0],$ n [1] );
}

返回sprintf(%02d\\\
,$ n [0]);


foreach(array(2,22,222,2.,2.11)as $ num){
echo pad($ num);
}

//返回02,22,222,02,02.11


I need to pad the integer part with 0, the integer part must be at least 2 characters

str_pad( 2    ,2,"0",STR_PAD_LEFT);// 02 -> works
str_pad( 22   ,2,"0",STR_PAD_LEFT);// 22 -> works
str_pad( 222  ,2,"0",STR_PAD_LEFT);// 222-> works
str_pad( 2.   ,2,"0",STR_PAD_LEFT);// 2. -> fails -> 02. or 02
str_pad( 2.11 ,2,"0",STR_PAD_LEFT);// 2.11-> fails -> 02.11

Is there simple code for that?

If possible the same in Java please

double x=2.11;
String.format("%02d%s", (int) x, String.valueOf(x-(int) x).substring(1))

is not only ugly but prints 02.10999999999999988

edit for Java: Java integer part padding

解决方案

You can also use printf() functions to pad the integer :

Something like (codepad):

<?php

function pad($n) {
    $n = explode('.', (string)$n);

    if (2 === count($n)) {
        return sprintf("%02d.%d\n", $n[0], $n[1]);    
    }

    return sprintf("%02d\n", $n[0]);    
}

foreach (array(2, 22, 222, 2., 2.11) as $num) {
    echo pad($num);
}

// returns 02, 22, 222, 02, 02.11

这篇关于PHP整数部分填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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