简体   繁体   中英

How to remove unwanted zeros from decimal number in Java (Selenium).But if last digit is not 0 then it should be displayed

I am querying lot of fields from Teradata and validating with the values displayed in UI using Selenium (Java). All my fields have only 3 decimal points.

For Eg,Number in DB = 4.199 is displayed as 4.199 in UI and Number in DB = 4.190 is displayed as 4.19 in UI and Number in DB = 4.100 is displayed as 4.1 in UI

When I assert, 4.190 and 4.19 are considered different by Selenium. I have lot of fields of this kind.How can I solve this?

Is there any other function like cast or round that can format the data in the way I want?

The best option you have is this:

boolean areTheyEqual = new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString())) == 0;

This way you are converting them into BigDecimals, then making use of the compareTo method which disregards scaling (so 1.2 is the same as 1.20).

I usually use BigDecimal for storing decimal when I want to do such manipulations. Here is an example, using the stripTrailingZeros() method:

BigDecimal b = new BigDecimal("2.210");
System.out.println(b.stripTrailingZeros());
//will print 2.21

You can always convert the values to BigDecimal and then check for equality, show them to UI formatted as you want, etc.

When using Selenium webElement.getText() the return is a String and when you comp 2.19 with 2.190 both are different so Assert will fail.

Can we try converting the String to Integer and perform the Assert action.

int num = Integer.parseInt(webElement.getText());

now the stored value in num is type Int so you can assert with another Int.

Else you can go with the suggestion above ( Use of BigDecimal)

As big decimal is not working for me I was searching for a regex and found it in the below link Remove trailing zero in Java

Its working perfectly.

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