Convert int strings to each other, limit float and double to retain a few decimal places, and generate random numbers

1. How to convert int type to character long type

int a = 1;
String aStr = a+"";

2. How to convert string type to int type

String aStr = "11";
int a = Integer.parseInt(aStr);

3. How to limit how many decimal places the double type retains:

        double a = 4.666666666;
        BigDecimal bigDecimal = new BigDecimal(a);
        /**
         * param1: 要保留几位小数
         * param2:四舍五入模式
         */
          double a2 = bigDecimal.setScale(2,    RoundingMode.HALF_UP).doubleValue();
        Log.e(TAG, "onCreate: "+a2+"" );  //打印结果为4.67

4. How to limit the float type to retain several decimal places:

float a = 4.666666f;
        BigDecimal bigDecimal = new BigDecimal(a);
        /**
         * param1: 要保留几位小数
         * param2:四舍五入模式
         */
        float a2 = bigDecimal.setScale(2, RoundingMode.HALF_UP).floatValue();
        Log.e(TAG, "onCreate: "+a2+"" );  //打印结果为4.67

5. How to generate random numbers:

//@return  a pseudorandom {@code double} greater than or equal to {@code 0.0} and less than {@code 1.0}.
        //Math.random()这个方法的解释的很清楚,产生一个double类型的随机数,>=0且<1;
        //通过(int)将double类型的强制转换为int
        //因此下面的数是>=0且<10的整数;
        int a = (int)(Math.random()*10);
        Log.e(TAG, "onCreate: "+a+"" );

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325539953&siteId=291194637