规划化数字

  • Post author:
  • Post category:其他


现在给你一个数字,请你规范化这一数字

输入

输入包含多种数据,每组数据一行一个数字,可能为小数,整数,负整数,负小数或者零。

数据保证数字没有前导0,保证不会出现欠0元的情况

输出

输出规范化后的内容

import java.util.*;
public class meituan2 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        //对输入类型的判断,统一用nextLine()接受
        while (s.hasNext()){
            String curr = s.nextLine();
            //处理小数部分
            if ( curr.contains(".")){
                //分割方法采用indexof记录特殊字符位置
                int indexof = curr.indexOf(".");
                String pre = curr.substring(0,indexof);
                String afe = curr.substring(indexof+1);
                if (curr.startsWith("-")){
                    pre = pre.substring(1);
                    //处理,
                    //这里用到StringBuilder,以便使用其强大的方法。
                    StringBuilder tem = new StringBuilder(pre);
                    int index = pre.length();
                    while (index>3){
                        index = index-3;
                        tem.insert(index,",");

                    }
                    //处理小数部分并拼接,这里不能省略了"."
                    if (afe.length()>=2){
                        afe = afe.substring(0,2);
                        curr = "("+"$"+tem+"."+afe+")";
                    }else {
                        curr = "("+"$"+tem+"."+afe+"0"+")";
                    }


                }else {
                    StringBuilder tem = new StringBuilder(pre);
                    int index = pre.length();
                    while (index>3){
                        index = index-3;
                        tem.insert(index,",");

                    }
                    if (afe.length()>=2){
                        afe = afe.substring(0,2);
                        curr = "$"+tem+"."+afe;
                    }else {
                        curr = "$"+tem+"."+afe+"0";
                    }


                }
            }else {
                if (curr.startsWith("-")){
                    curr = curr.substring(1);
                    StringBuilder tem = new StringBuilder(curr);
                    int index = curr.length();
                    while (index>3){
                        index = index-3;
                        tem.insert(index,",");

                    }
                    curr = "("+"$"+tem+".00"+")";

                }else {
                    StringBuilder tem = new StringBuilder(curr);
                    int index = curr.length();
                    while (index>3){
                        index = index-3;
                        tem.insert(index,",");

                    }
                    curr = "$"+tem+".00";
                }
            }

            System.out.println(curr);
        }
    }
}



版权声明:本文为weixin_43084620原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。