当前位置: 技术问答>java相关
如果限制float小数点后面的位数
来源: 互联网 发布时间:2017-03-15
本文导语: 我只想要两位小数 | DecimalFormat df = new DecimalFormat("0.##"); | /** * 精确到小数点后的nFmt位数(现在暂时只精确到2位) * * @deprecated this format fucntion is unsafe a...
我只想要两位小数
|
DecimalFormat df = new DecimalFormat("0.##");
|
/**
* 精确到小数点后的nFmt位数(现在暂时只精确到2位)
*
* @deprecated this format fucntion is unsafe and uncompatible.
* @param dfValue the double value to be format
* @param nFmt format is requested.
* @return String
*/
public static String formatDouble( double dfValue , int nFmt ) {
String strResult;
int nDecimalLen = 2 ;//digital preserved after decimal point.
switch( nFmt ) {
default:
case Function.FMT_NUM_NORMAL:
strResult = String.valueOf( dfValue );
break;
case Function.FMT_NUM_NODELIMA:
case Function.FMT_NUM_COMMADELIMA:
dfValue += 0.0050001 ;
strResult = String.valueOf( dfValue );
strResult = strResult.substring( 0 , strResult.indexOf( '.' ) + nDecimalLen + 1 );
if( nFmt == Function.FMT_NUM_COMMADELIMA ) {
int nLen = strResult.length() - nDecimalLen - 2 ;
int nIndex = nLen % 3 ;
StringBuffer sbResult = new StringBuffer( 40 ) ;
sbResult.append( strResult.substring( 0 , nIndex ) ) ;
for( ; nIndex
* 精确到小数点后的nFmt位数(现在暂时只精确到2位)
*
* @deprecated this format fucntion is unsafe and uncompatible.
* @param dfValue the double value to be format
* @param nFmt format is requested.
* @return String
*/
public static String formatDouble( double dfValue , int nFmt ) {
String strResult;
int nDecimalLen = 2 ;//digital preserved after decimal point.
switch( nFmt ) {
default:
case Function.FMT_NUM_NORMAL:
strResult = String.valueOf( dfValue );
break;
case Function.FMT_NUM_NODELIMA:
case Function.FMT_NUM_COMMADELIMA:
dfValue += 0.0050001 ;
strResult = String.valueOf( dfValue );
strResult = strResult.substring( 0 , strResult.indexOf( '.' ) + nDecimalLen + 1 );
if( nFmt == Function.FMT_NUM_COMMADELIMA ) {
int nLen = strResult.length() - nDecimalLen - 2 ;
int nIndex = nLen % 3 ;
StringBuffer sbResult = new StringBuffer( 40 ) ;
sbResult.append( strResult.substring( 0 , nIndex ) ) ;
for( ; nIndex