简体   繁体   中英

Extracting digit values from before and after decimal points in Java

I have 2 values

String latitude = "37.348541"; String longitude = "-121.88627";

I would like to extract like the values as below with out any rounding up the values.

latitude = "37.34"; longitude = "-121.88";

I tried using DecimalFormat.format, but it does some round up and I want to extract an exact value.

For example:

String latitude  = "37.348541";
int i = latitude.indexOf(".");
if(i > 0 && i < latitude.length()-2) latitude  = latitude.substring(i, i+2);

You can use the BigDecimal class and the ROUND_DOWN option. So the code could look like this:

BigDecimal number = new BigDecimal("123.13298");
BigDecimal roundedNumber = number.setScale(2, BigDecimal.ROUND_DOWN);
System.out.println(roundedNumber);

Otherwise you can also use the native double and the Math.floor or the Math.ceil method:

double number = 123.13598;
double roundedNumber = (number < 0 ? Math.ceil(number * 100) : Math.floor(number * 100)) / 100;
System.out.println(roundedNumber);

You can define a function using String#substring and String#indexOf as shown below:

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(getNumberUptoTwoDecimalPlaces("37.348541"));
        System.out.println(getNumberUptoTwoDecimalPlaces("-121.88627"));
        System.out.println(getNumberUptoTwoDecimalPlaces("-121.8"));
        System.out.println(getNumberUptoTwoDecimalPlaces("-121.88"));
        System.out.println(getNumberUptoTwoDecimalPlaces("-121.889"));
    }

    static String getNumberUptoTwoDecimalPlaces(String number) {
        int indexOfPoint = number.indexOf('.');
        if (indexOfPoint != -1 && number.length() >= indexOfPoint + 3) {
            return number.substring(0, indexOfPoint + 3);
        } else {
            return number;
        }
    }
}

Output:

37.34
-121.88
-121.8
-121.88
-121.88

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM