Implementation operation of java sub conversion and sub conversion

  • 2021-08-21 20:35:24
  • OfStack

Dividing-transformational element


private String fenToYuan(String amount){
  NumberFormat format = NumberFormat.getInstance();
  try{
    Number number = format.parse(amount);
    double temp = number.doubleValue() / 100.0;
    format.setGroupingUsed(false);
    //  Sets the maximum number of digits allowed for the returned decimal part 
    format.setMaximumFractionDigits(2);
    amount = format.format(temp);
  } catch (ParseException e){
    e.printStackTrace();
  }
  return amount;
}

Convert to points


private String yuanToFen(String amount){
  NumberFormat format = NumberFormat.getInstance();
  try{
    Number number = format.parse(amount);
    double temp = number.doubleValue() * 100.0;
    format.setGroupingUsed(false);
    //  Sets the maximum number of digits allowed for the decimal part of the returned number 
    format.setMaximumFractionDigits(0);
    amount = format.format(temp);
  } catch (ParseException e){
    e.PrintStackTrace();
  }
  return amount;
}

Supplement: java sub-transformer decimal formatting

I won't talk too much, let's just look at the code ~


public class NumberUtils {
  public static String format(double f) {
    DecimalFormat df = new DecimalFormat("#.##");
    return df.format(f) ;
  }
  public static String fenToYuan(int f) {
    return format(f/100.0) ;
  }
  public static void main(String[] args) {
    System.out.println(fenToYuan(3));
    System.out.println(fenToYuan(33));
    System.out.println(fenToYuan(333));
    System.out.println(fenToYuan(3333));
    System.out.println(fenToYuan(33333));
  }
}

Related articles: