Home > front end >  How to truncate decimal value in a text
How to truncate decimal value in a text

Time:04-29

So, I need to show a string in UI which has both numbers and text together. Something like this,

10.289 Mbps

and I wanted to remove .289 and just show 10 Mbps

I tried a lot of options like setting text as

String rounded = String.format("%.0f", speedValue);

But nothing seems to be working for me. Appreciate any help.

CodePudding user response:

something like this can work:

string = "10.289 Mbps"
string_list = string.split(" ")
number = string_list[0]
number = float(number)
print(round(number))

basically isolate the number bu removing 'Mbps' then cast it to a float value and round it to get an integer.

CodePudding user response:

try this

String str = "10.289 Mbps";

String[] strArray = str.split(" ");
    
Long roundedValue = Math.round(Double.valueOf(strArray[0]));
    
String resultStr = roundedValue.toString()   " "   strArray[1];

System.out.println(resultStr);

CodePudding user response:

This can be possible in many ways.

  1. Split String

    String inputStr = "10.289 Mbps";
    
    String[] splited = inputStr.split(" ");
    Double val = Double.parseDouble(splited[0]);
    System.out.println("Value : " val.intValue() " " splited[1]);
    
  2. Regx

    Pattern pattern = Pattern.compile("(([0-9] )(.)?([0-9] )?) ([A-Z,a-z] )", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.find())
    {
        System.out.println("Value : " matcher.group(2) " " matcher.group(5));
    }
    
  • Related