简体   繁体   English

格式化双精度数,左侧和右侧为零

[英]format double with zeros on left and right side

I want to format a double with zeroes on the left and right as needed. 我想根据需要格式化在左侧和右侧带有零的双精度型。

double myVal = 12.456;

Want string to be "012.456000" 希望字符串为"012.456000"

I've tried: 我试过了:

String.format("%03.06f", myVal);

and other variations but it doesn't seem to format the text on the left side of the decimal place. 和其他变体,但似乎无法格式化小数点左侧的文本。

I'd prefer not to bring in a third party lib for this, if possible. 如果可能的话,我不希望为此引入第三方库。

Use java.text.DecimalFormat : 使用java.text.DecimalFormat

double myVal = 12.456; 
DecimalFormat formatter = new DecimalFormat("000.000000");      
System.out.println(formatter.format(myVal));

This is the i18n (locale-specific) way: 这是i18n(特定于语言环境)的方式:

double myVal = 12.456;
Locale locale = Locale.getDefault(); //replace this with actual locale
NumberFormat nf = NumberFormat.getNumberInstance(locale);
nf.setMinimumIntegerDigits(3);
nf.setMinimumFractionDigits(6);
System.out.println(nf.format(myVal)); //012.456000

I believe this is what you are looking for using the decimal format will give you however many zeros you want on the left and or right side of what you are formatting. 我相信这是您在寻找要使用十进制格式的内容,但是在格式设置的左侧和/或右侧会出现许多零。

import java.text.*;
public class leftsideformat
{

  public static void main(String[] args)
  {
    double myVal  =12.456;
    DecimalFormat leftside = new DecimalFormat("000.0000000000");
    System.out.println(leftside.format(myVal));
  }

}

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

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