/*
 * MittTallformatInn.java   E.L. 2000-01-31
 *
 * Klassen beskriver et format som egner seg for innlesing av et enkelt tall.
 * Tallet må enten være desimaltall med komma som desimalskille, eller
 * et heltall. Fortegn godtas ikke.
 */

package mittBibliotek;

import java.text.*;
public class MittTallformatInn {
  NumberFormat tallformat = NumberFormat.getNumberInstance();

  public double tolkPositivDouble(String tallet) throws ParseException {
    tallet = tallet.trim();
    int antKomma = 0;
    int pos = 0;
    boolean ok = true;
    while (pos < tallet.length() && ok){
      char tegn = tallet.charAt(pos);
      if (tegn == ',') antKomma ++;
      else if (!Character.isDigit(tegn)) ok = false;
      if (antKomma > 1) ok = false;
      pos++;
    }
    if (!ok) throw new ParseException("Ugyldig tallformat", pos);
    Number tall = (Number) tallformat.parse(tallet);
    return tall.doubleValue();
  }

  public int tolkPositivInt(String tallet) throws ParseException {
    tallet = tallet.trim();
    int pos = 0;
    boolean ok = true;
    while (pos < tallet.length() && ok){
      char tegn = tallet.charAt(pos);
      if (!Character.isDigit(tegn)) ok = false;
      pos++;
    }
    if (!ok) throw new ParseException("Ugyldig tallformat", pos);
    Long tall = (Long) tallformat.parse(tallet);
    return tall.intValue();
  }
}
