Java:可变十进制长度格式化输出

时间:2018-02-21 15:36:13

标签: java printf formatted-text

设a为任何浮点数:

// Change ([ngModel]) to [(ngModel)]
<mat-select [(ngModel)]="myValue">
    // value={{o}} to value="{{allValues[o]}}"
    <mat-option *ngFor="let o of valueOptions" value="{{allValues[o]}}">{{o}}</mat-option>

然后我从标准输入中得到小数位数:

float a = 13.1234567;

如何在点之后打印带有'decLen'小数位的'a'? 我需要打印

decLen = 3:

import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int decLen = sc.nextInt();

decLen = 6:

13.123

decLen = 0:

13.123456

Java库中是否存在任何能够执行此类任务的格式化方法?

1 个答案:

答案 0 :(得分:-1)

有点黑客,但这会奏效:

frame.getContentPane().add(desktop, BorderLayout.CENTER);

打印:

    double[] doubles = {13.123, 13.123456, 13};
    for (int i = 0; i < doubles.length; i++) {
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubles[i]));
        System.out.println("decLen = " + bigDecimal.stripTrailingZeros().scale());
    };

将float或double转换为字符串将防止在创建BigDecimal时出现舍入错误。