将double
与String
进行相互转换,并执行相加、相减等操作,并可以保留一定的小数位数。
1. double
与 String
之间的转换
double
转 String
-
使用
Double.toString(double d)
方法:javadouble num = 123.456; String str = Double.toString(num);
-
使用
String.valueOf(double d)
方法:javadouble num = 123.456; String str = String.valueOf(num);
String
转 double
-
使用
Double.parseDouble(String s)
方法:javaString str = "123.456"; double num = Double.parseDouble(str);
-
使用
Double.valueOf(String s)
方法:javaString str = "123.456"; double num = Double.valueOf(str);
2. 基本的算术操作
可以直接使用算术运算符进行相加、相减、相乘和相除操作。
java
public class ArithmeticOperations {
public static void main(String[] args) {
double num1 = 10.5;
double num2 = 3.2;
// 相加 double sum = num1 + num2;
System.out.println("Sum: " + sum);
// 相减 double difference = num1 - num2;
System.out.println("Difference: " + difference);
// 相乘 double product = num1 * num2;
System.out.println("Product: " + product);
// 相除 double quotient = num1 / num2;
System.out.println("Quotient: " + quotient);
// 取余 double remainder = num1 % num2;
System.out.println("Remainder: " + remainder); } }
3. 保留小数位数
使用 BigDecimal
类可以精确地保留小数位数。
创建 BigDecimal
对象
-
通过
double
创建:javaBigDecimal bd = new BigDecimal(num);
-
通过
String
创建:javaBigDecimal bd = new BigDecimal("123.456");
设置小数位数
-
使用
setScale(int newScale, RoundingMode roundingMode)
方法:javaBigDecimal bd = new BigDecimal("123.456789"); BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP); // 保留两位小数,四舍五入 System.out.println("Rounded: " + rounded);
4. 综合代码
java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class DoubleStringConversionAndArithmetic {
public static void main(String[] args) {
// String 转 double
String str1 = "45.6789";
double num1 = Double.parseDouble(str1);
System.out.println("String to double: " + num1);
// double 转 String double num2 = 123.456;
String str2 = Double.toString(num2);
System.out.println("Double to String: " + str2);
// 相加并保留两位小数 double sum = num1 + num2;
BigDecimal bdSum = new BigDecimal(sum).setScale(2, RoundingMode.HALF_UP);
System.out.println("Sum (2 decimal places): " + bdSum);
// 相减并保留两位小数 double difference = num1 - num2;
BigDecimal bdDifference = new BigDecimal(difference).setScale(2, RoundingMode.HALF_UP);
System.out.println("Difference (2 decimal places): " + bdDifference);
// 相乘并保留两位小数 double product = num1 * num2;
BigDecimal bdProduct = new BigDecimal(product).setScale(2, RoundingMode.HALF_UP);
System.out.println("Product (2 decimal places): " + bdProduct);
// 相除并保留两位小数 double quotient = num1 / num2;
BigDecimal bdQuotient = new BigDecimal(quotient).setScale(2, RoundingMode.HALF_UP);
System.out.println("Quotient (2 decimal places): " + bdQuotient); } }