Java Double to String double2str(double d, int noOfDecimalDigit)

Here you can find the source of double2str(double d, int noOfDecimalDigit)

Description

doublestr

License

Open Source License

Declaration

public static String double2str(double d, int noOfDecimalDigit) 

Method Source Code

//package com.java2s;
/*   //from  w  w  w.j a va  2  s.  co  m
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
     
Author : Faisal Adnan
Email  : faisal.adnan@gmail.com
    
 */

public class Main {
    public static String double2str(double d, int noOfDecimalDigit) {
        String str = "";
        String ds = Double.toString(d);
        if (d == 0)
            ds = "0." + generateZeros(noOfDecimalDigit);
        if (ds.length() < noOfDecimalDigit + 2)
            ds = ds + generateZeros(noOfDecimalDigit + 2 - ds.length());
        int delimiterIndex = ds.indexOf(".");
        int decLen = ds.substring(delimiterIndex, ds.length()).length() - 1;
        if (decLen < noOfDecimalDigit + 2)
            ds = ds + generateZeros(noOfDecimalDigit + 2 - decLen);
        str = ds.substring(0, delimiterIndex) + ds.substring(delimiterIndex, delimiterIndex + noOfDecimalDigit + 1);
        return str;
    }

    public static String generateZeros(int n) {
        String res = "";
        for (int i = 0; i < n; i++) {
            res = res + "0";
        }
        return res;
    }
}

Related

  1. convertDoubleToString(double value)
  2. convertDoubleToString(double value)
  3. double2str(double amount, int length)
  4. double2string(double doubledata)
  5. double2String(double[] v)
  6. doubleToStr(Double d)
  7. doubleToStr(Double valor)