简体   繁体   中英

How to convert string with int to string with double?

I am building a calculator, for the calculator to work I need to convert all the int numbers to double numbers in my string. For example, if I have this string: 3*8+5/2-4, I want to convert him to: 3.0*8.0+5.0/2.0-4.0. How can I do this?

EDIT: If I have this string: 3.0*8.0+5.0/2.0-4, I want to convert him to: 3.0*8.0+5.0/2.0-4.0

you can replace string by regex using String#replaceAll , for example:

String regex = "(?<=^|[+/(*)-])(\\d+)(?=[+/(*)-]|$)";

// $1 references to the first captured group ---v
String result1 = "3*8+5/2-4".replaceAll(regex, "$1.0");
//     ^--- "3.0*8.0+5.0/2.0-4.0"

String result2 = "3.0*8+5/2-4.0".replaceAll(regex, "$1.0");
//     ^--- "3.0*8.0+5.0/2.0-4.0"

String result3 = "3.0*(8+5)/(2-4.0)".replaceAll(regex, "$1.0");
//     ^--- "3.0*(8.0+5.0)/(2.0-4.0)"

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