如何将数字格式化为一定数量的小数位数和逗号分隔符? [英] How to format Number to certain number of Decimal Places plus comma separators?

查看:60
本文介绍了如何将数字格式化为一定数量的小数位数和逗号分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This relates to my previous question, which can be found at:

数学方程式结果显示时丢失小数点

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

In my assignment, we have to calculate the perimeter of an isosceles trapezoid. The perimeter the needs to be formatted to 4 decimal places. If the result after the decimal place is all zeros, then don’t display the zeros. (Example: the results are 12.000000 what will be displayed is 12.) Also if the result is greater than 1000 before the decimal, then the comma must be displayed. (Example: the results are 1234.56781 what will be display is 1,234.5678). We are required to use the decimal format class. Here is my code:

//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 );
   }
}

我将如何格式化周边的打印件,使其使用十进制格式类并满足要求?

How would I format the print out for the perimeter so that it uses the decimal format class and satisfies the requirements?

推荐答案

使用和

有多种定义此方法的方法,请参阅所需内容.您还可以使用十进制格式

There are various ways to define this please see what you need. You can also use Decimal Format

这篇关于如何将数字格式化为一定数量的小数位数和逗号分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆