简体   繁体   English

如何将具有int的字符串转换为具有double的字符串?

[英]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. 我正在构建一个计算器,为了使计算器正常工作,我需要将所有int数转换为字符串中的双数。 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. 例如,如果我有以下字符串:3 * 8 + 5 / 2-4,我想将其转换为: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 编辑:如果我有此字符串:3.0 * 8.0 + 5.0 / 2.0-4,我想将他转换为:3.0 * 8.0 + 5.0 / 2.0-4.0

you can replace string by regex using String#replaceAll , for example: 您可以使用String#replaceAll用正则表达式替换字符串,例如:

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)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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