/*  
 *  src/org/thalia/bio/util/NumberFormat.java
 * 
 *  $Author: veyrieras $, $Date: 2006-10-17 15:41:55 $, $Version$
 *
 *  MetaQTL : a Java package for QTL Meta-Analysis
 * 
 *  Copyright (C) 2003-2006  Jean-Baptiste Veyrieras, INRA, France.
 *
 *  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 * 
 */
package org.metaqtl.bio.util;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.lang.String;

/**
 * @author jveyrier
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public final class NumberFormat {
	
	/**
	 * 
	 * @param d
	 * @return
	 */
	public static String formatDouble(double d) {
		 if (d != Double.NaN) {
			 java.text.NumberFormat form = java.text.NumberFormat.getInstance();
			 if (form instanceof DecimalFormat) {
			 	 DecimalFormatSymbols df = ((DecimalFormat) form).getDecimalFormatSymbols(); 
			     df.setDecimalSeparator('.');
			     df.setGroupingSeparator(' ');
			     ((DecimalFormat) form).setDecimalFormatSymbols(df);
			     form.setMaximumFractionDigits(2);
			     String s = form.format(d);
			     s = s.replaceAll(" ",""); // due to the grouping separator
			     return s;
			 } else {
				 DecimalFormat df = new DecimalFormat("%.2f");
				 StringBuffer tmp  = new StringBuffer();
				 tmp = df.format (d, tmp, null);
				 return tmp.toString(); 
			 }
		 } else {
		 	return "NaN";
		 }
	}
	/**
	 * This method parse the given string to a double value. If the 
	 * string is not valid <code>Double.NaN</code> is returned.
	 * Note that this method is 'coma'/'dot' tolerant.
	 *   
	 * @param value
	 * @return
	 */
	public static double parseDouble(String value) {
		try { 
			return Double.parseDouble(value);
		} catch (NumberFormatException e1) {
			/* May be its due to the fact that a coma is used instead of
			 * a point */
			try {
				return Double.parseDouble(value.replace(',', '.'));
			} catch (NumberFormatException e2) {
				return Double.NaN;
			}
		}
	}
}
