Java Cut String After 2 Decimal Digits

Trim from String after decimal places to 18 places in java - roundoff not required)

Use regex for a one line solution:

str = str.replaceAll("(?<=\\..{18}).*", "");

See live demo.

Trim string to two decimal places

You can use a regex to find the numbers you want, and then reconstruct the string:

function convert(inputStr) {
const groups = inputStr.match(/\((?<r>[\d]*).*, ?(?<g>[\d]*).*, ?(?<b>[\d]*).*, ?(?<a>[\d]*\.?\d{0,2}).*\)/).groups;
return `rgba(${groups.r}, ${groups.g}, ${groups.b}, ${groups.a})`;
}
// Function call
convert("rgba(244.235, 3.234, 3.236, 0.84839234)");

How to split a double number by dot into two decimal numbers in Java?

You can try this way too

    double val=1.9;
String[] arr=String.valueOf(val).split("\\.");
int[] intArr=new int[2];
intArr[0]=Integer.parseInt(arr[0]); // 1
intArr[1]=Integer.parseInt(arr[1]); // 9

How to nicely format floating numbers to string without unnecessary decimal 0's

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}

Produces:

232
0.18
1237875192
4.58
0
1.2345

And does not rely on string manipulation.



Related Topics



Leave a reply



Submit