如何在数字小数点后的空位处添加零?

huangapple go评论66阅读模式
英文:

How can I append zeroes in place of empty spaces after the decimal in a number?

问题

这是问题,我陷入了困境,不知道如何在Java中在小数点后的空位处添加零。\n链接描述在这里\n\n 1: https://www.hackerrank.com/challenges/plus-minus/problem

英文:

This is the question and I am stuck that how can I append zeroes in place of empty spaces after the decimal in java.
enter link description here

答案1

得分: 1

一个java.text.DecimalFormat实例可以为您完成此操作,以下是一个示例:

new DecimalFormat("###,##0.00000").format(1.23);    // => 1.23000
new DecimalFormat("###,##0.00000").format(0.987643); // => 0.98764

请注意,上述代码中的格式字符串 "###,##0.00000" 指定了数字格式的模式。

英文:

A java.text.DecimalFormat instance can do this for you, here is an example:

new DecimalFormat("#,##0.00000").format(1.23);    // => 1.23000
new DecimalFormat("#,##0.00000").format(.987643); // => 0.98764

答案2

得分: 1

可以使用 DecimalFormat#format 来实现。

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
    public static void main(String[] args) {
        // 定义格式化器
        NumberFormat formatter = new DecimalFormat("0.000000");

        // 测试
        System.out.println(formatter.format(0.3));
        System.out.println(formatter.format(123.3));
        System.out.println(formatter.format(0.335));
        System.out.println(formatter.format(0.0));
        System.out.println(formatter.format(1.0));
    }
}

输出:

0.300000
123.300000
0.335000
0.000000
1.000000
英文:

You can use DecimalFormat#format to do so.

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
	public static void main(String[] args) {
		// Define the formatter
		NumberFormat formatter = new DecimalFormat("0.000000");

		// Tests
		System.out.println(formatter.format(0.3));
		System.out.println(formatter.format(123.3));
		System.out.println(formatter.format(0.335));
		System.out.println(formatter.format(0.0));
		System.out.println(formatter.format(1.0));
	}
}

Output:

0.300000
123.300000
0.335000
0.000000
1.000000

答案3

得分: 1

任何字符串格式化工具都可以做到。

 String s = String.format("%.30f", 1.23);

或者

 System.out.printf("%.30f %n", 1.23);

这些示例会在小数点后提供30位小数位。

英文:

Any string formatter can do it.

 String s = String.format("%.30f", 1.23);

or

 System.out.printf("%.30f %n", 1.23);

Those examples give you 30 places after the decimal point.

huangapple
  • 本文由 发表于 2020年9月27日 21:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64089042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定