PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to add 2 decimal places having 0s to an array

 August 10, 2022     decimal, floating-point, java     No comments   

Issue

I want to print precision of 2 for all elements in my array.

For example, if I input 11.00, I expect output:

[11.00, 11.04, 11.09, 11.15, 11.19, 11.22]

but I get:

[11.0, 11.04, 11.09, 11.15, 11.19, 11.22]

Where the first element is missing trailing zero.

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;

import static java.lang.Math.*;
public class Main{
  public static void main (String[] args){
    Scanner s = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat(".00");
    df.setMaximumFractionDigits(2);
    float a=s.nextFloat();
    float arr[]= new float[6];
    // arr[0]=Float.valueOf((df.format(a+0.001)));
    arr[0]=a;
    arr[1]=a+(float)(0.04);
    arr[2]=a+(float)(0.09);
    arr[3]=a+(float)(0.15);
    arr[4]=a+(float)(0.19);
    arr[5]=a+(float)(0.22);
    System.out.println(Arrays.toString(arr));
    
  }
}

Solution

Let's start with why doesn't it work? From Arrays.toString docs:

Elements are converted to strings as by String.valueOf(float).

The implementation of String.valueOf(float) is:

public static String valueOf(float f) {
    return Float.toString(f);
}

Therefore the df declared in your code snippet is never used.

What can you do? As @Koenigsberg mentioned in his answer, you can iterate over the array, and then add brackets on the sides, and commas between the elements.

If you can use double instead of floats, you can use java streams. Code sample will be:

System.out.println("[" + Arrays.stream(arr).mapToObj(df::format).collect(Collectors.joining(", ")) + "]");

If you can't use doubles, you can just iterate over the indices of arr:

System.out.println("[" + IntStream.range(0, arr.length).mapToObj(i -> df.format(arr[i])).collect(Collectors.joining( ", ")) + "]");


Answered By - Tomer Shetah
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing