gpt4 book ai didi

java - 如何将数字格式化为一定数量的小数位加逗号分隔符?

转载 作者:行者123 更新时间:2023-12-01 07:25:17 36 4
gpt4 key购买 nike

这与我之前的问题有关,可以在以下位置找到:

Math equation result loses decimals when displayed

在我的作业中,我们必须计算等腰梯形的周长。周长需要格式化为小数点后 4 位。如果之后的结果小数点全为零,则不显示零。 (例如:结果是 12.000000 什么将显示为 12。)此外,如果结果小数点前大于 1000,则必须显示逗号。 (例如:结果是 1234.56781 将显示的是1,234.5678)。我们需要使用十进制格式类。这是我的代码:

//Kyle Collins
/*This program calculates the area and perimeter of an isosceles trapezoid, as well
as the diagonal of the isosceles trapezoid.
*/

import java.util.Scanner;
import java.lang.Math;
import java.text.*;

public class CSCD210Lab2
{
public static void main (String [] args)
{
Scanner mathInput = new Scanner(System.in);

//declare variables

double topLength, bottomLength, height,perimPt1,perimPt2;


//Get user input
System.out.print("Please Enter Length of the Top of Isosceles Trapezoid: ") ;
topLength = mathInput.nextDouble() ;
mathInput.nextLine() ;

System.out.print("Please Enter Length of the Bottom of Isosceles Trapezoid: ") ;
bottomLength = mathInput.nextDouble() ;
mathInput.nextLine() ;

System.out.print("Please Enter Height of Isosceles Trapezoid: ") ;
height = mathInput.nextDouble() ;
mathInput.nextLine() ;

perimPt1 = ((bottomLength - topLength)/2);
perimPt2 =(Math.sqrt(Math.pow(perimPt1,2) + Math.pow(height,2)));

double trapArea = ((topLength + bottomLength)/2*(height));
double trapDiag = (Math.sqrt(topLength*bottomLength + Math.pow(height,2)));
double trapPerim = 2*(perimPt2) + (topLength + bottomLength);

//Print the results
System.out.println();
System.out.println("The Area of the Isosceles Trapezoid is: "+trapArea);
System.out.printf("The Diagonal of the isosceles trapezoid is: %-10.3f%n",trapDiag);
System.out.printf("The Perimeter of the Isosceles Trapezoid is: "+trapPerim );
}
}

如何格式化周长的打印输出,以便它使用十进制格式类并满足要求?

最佳答案

使用和String.format()

String.format("%.2f", (double)value);

有多种方法可以定义它,请看看您需要什么。您还可以使用Decimal Format

关于java - 如何将数字格式化为一定数量的小数位加逗号分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26128526/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com