页面有输出附件大小,由于数据库里存在都是字节大小,所以在展示的时候都要进行格式化一下。
下面是采用java代码:
- String filename = "";
- float size=0f;
- String unit="";//单位
- float attchSize = Float.parseFloat(filesize);
- if(attchSize<1024){
- size = (float)(attchSize);
- unit=" 字节";
- }else{
- float k = (float)(attchSize/1024);
- if(k<1024){
- size = (float)(k);
- unit = " KB";
- }else{
- float m = (float)(k/1024);
- if(m<1024){
- size = (float)(m);
- unit = " MB";
- }else{
- size = (float)(m/1024);
- unit =" GB";
- }
- }
- }
- DecimalFormat formater=new DecimalFormat("#0.##");
- filename =formater.format(size).toString();
- if((filename .indexOf(".00"))!=-1){
- filename =filename .substring(0,filename .indexOf(".00"));
- }
- filename +=unit;
String filename = "";
float size=0f;
String unit="";//单位
float attchSize = Float.parseFloat(filesize);
if(attchSize<1024){
size = (float)(attchSize);
unit=" 字节";
}else{
float k = (float)(attchSize/1024);
if(k<1024){
size = (float)(k);
unit = " KB";
}else{
float m = (float)(k/1024);
if(m<1024){
size = (float)(m);
unit = " MB";
}else{
size = (float)(m/1024);
unit =" GB";
}
}
}
DecimalFormat formater=new DecimalFormat("#0.##");
filename =formater.format(size).toString();
if((filename .indexOf(".00"))!=-1){
filename =filename .substring(0,filename .indexOf(".00"));
}
filename +=unit;
不过我感觉这样写不是太好,太多if,else,并且我现在是采用Ext来做前台框架,希望通过renderer来进行格式化处理。
网上找到一个php版本的,代码如下:
- <? php
- function setupSize( $fileSize ) {
- $size = sprintf ( " %u " , $fileSize );
- $sizename = array ( " Bytes " , " KB " , " MB " , " GB " , " TB " , " PB " , " EB " , " ZB " , " YB " );
- return round ( $size / pow ( 1024 , ( $i = floor ( log ( $size , 1024 )))) , 3 ) . $sizename [ $i ];
- }
- echo setupSize( ' 200000 ' )
- ?>