How do I round to two decimal places on MPAndroidChart? - rounding

I've made a line chart on MPAndroidChart and would like the output to only show two decimal places.
This is the code I've used to round off the data. The data was originally in a Long ArrayList. I converted it to float because Android Studio wanted it to be in float.
private static final DecimalFormat df = new DecimalFormat("0.00");
ArrayList<Entry> dataVals = new ArrayList<Entry>();
for (i=0; i<sampleSize; i++){
float k = list.get(i)/1000;
df.setRoundingMode(RoundingMode.UP);
df.format(k);
dataVals.add(new Entry((float) (i), k));
}
The datapoints sometimes show two decimal places and sometimes three. I can't work out why.
Does anyone know how to ensure it always rounds off to decimal places?

// Create a custom ValueFormatter that rounds to two decimal places
ValueFormatter formatter = new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return String.format(Locale.getDefault(), "%.2f", value);
}
};
// Set the ValueFormatter on the chart
chart.getAxisLeft().setValueFormatter(formatter);

If you want to control the formatting of the numbers displayed over each data point, you have to define a value formatter on the data set (not the axis - which controls the format of the numbers on the chart axes). For example, to show 2 decimal places for all points, you would add this (using your existing decimal formatter df):
dataSet.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return df.format(value);
}
});
A more complete example:
// declare the formatter as a class member
private static final DecimalFormat df = new DecimalFormat("0.00");
// Prepare your list of Entries (no need to do anything with the
// formatter here)
ArrayList<Entry> dataVals = new ArrayList<Entry>();
for (i=0; i<sampleSize; i++){
float k = list.get(i)/1000;
dataVals.add(new Entry((float) (i), k));
}
// set the formatter mode (only need to call this once,
// not inside the loop)
df.setRoundingMode(RoundingMode.UP);
// create a LineDataSet from your list of entries
LineDataSet dataSet = new LineDataSet(dataVals, "Values");
// Set a value formatter on the data set (to control
// how the numbers over the points are shown) and
// call your data formatter here
dataSet.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return df.format(value);
}
});
Note You can also define this formatter on the LineData object instead of the LineDataSet if you have multiple data sets and want to apply the same formatter to all of them. The syntax is the same as setting it on the LineDataSet.
LineData data = new LineData(dataSet);
data.setValueFormatter(new ValueFormatter() {
#Override
public String getFormattedValue(float value) {
return df.format(value);
}
});

Related

Please I have A playfair cipher, it converts String inputs to Int, but I want Hex

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
This is the public class
public class Process {
private String keywordAsString = "";
private String keyword = "";
// ArrayList to hold the letters of the keyword with duplicates removed.
private ArrayList<Integer> keywordAsIntsNoDup = new ArrayList<Integer>(0);
// Map for removing all duplicate letters in the keyword.
private Map<Integer, Integer> keywordLetters = new LinkedHashMap<Integer, Integer>(0);
// ArrayList to hold all 256 ASCII characters (as integers).
private ArrayList<Integer> asciiArray = new ArrayList<Integer>(0);
// ArrayList for storing the message from the file.
ArrayList<Integer> fileMessageAsInteger = new ArrayList<Integer>(0);
// Constructor
public void process() {
}
public void processKeyword(String keyword) {
// Copy incoming keyword String
this.keywordAsString = keyword;
// Pass incoming keyword String to the removeDuplicate method.
// removeDuplicate will first convert the letters to Integers,
// then remove any duplicate letters.
// Store the result in the keywordAsIntsNoDup ArrayList
this.keywordAsIntsNoDup = removeDuplicates(this.keywordAsString);
// Create ArrayList and fill it with all 256 ASCII characters (as integers).
createAsciiArr();
// Remove the keyword letters from the asciiArray.
for (int i=0; i<this.keywordAsIntsNoDup.size(); i++) {
Integer letterToSearchFor = this.keywordAsIntsNoDup.get(i);
if (this.asciiArray.contains(letterToSearchFor))
{
this.asciiArray.remove(letterToSearchFor);
}
}
}// END processKeyword()
public ArrayList<Integer> removeDuplicates(String keyword) {
// Copy incoming keyword String
this.keyword = keyword;
I really would appreciate if someone would help me Java is really no piece of cake.
// Loop through the keywordAsIntArray ArrayList, putting each 'letter' of the keyword into the map.
// Duplicate letters will be overridden, so the map will contain the keyword without any duplicates.
for (int i=0; i
// Put the maps' key set (which holds the 'letters') into an ArrayList.
// This will make it easier to put the 'letters' into the Table later.
ArrayList<Integer> keyslist = new ArrayList<Integer>(this.keywordLetters.keySet());
System.out.println("\n" + "map.keySet() from keyslist ArrayList = " + keyslist.toString());
return keyslist;
}
public void createAsciiArr() {
// Use an enhanced for loop to fill the asciiArray ArrayList
// with all 256 ASCII characters as integers.
for (int i=0; i<256; i++) {
this.asciiArray.add(i);
}
}// END createAsciiArr()
}// END class
Please I want to input String as keyword, then get back hex values as the encrypted code and not integers. Also Please I have more of the codes I dont really understand,am really new to Java. Please can anyone help me.

Need help understand how Strings work in my method

I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly

Change String length or decimal precision of field attribute dynamically

I'm trying to use setup data from one table to allow me to format fields on the fly / dynamically. I know I can change field names and visibility based on the PXUIFieldAttribute class, but changing the precision or string length is a bit trickier, obviously. From the research I've done, I've come up with the following example code that seems like it should work - but I get the error:
"Unable to cast object of type 'PX.Data.PXUIFieldAttribute' to type 'PX.Data.PXDBDecimalAttribute'.
I don't see why this is occurring...
protected virtual void xTACOpenSourceDetail_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
var osd = (PXCache)sender;
foreach (PXDBDecimalAttribute attribute in this.Caches<xTACOpenSourceDetail>().GetAttributes("Number1"))
{
PXDBDecimalAttribute someAttribute = attribute as PXDBDecimalAttribute;
if (someAttribute != null)
{
someAttribute.DBProperties._precision = 4;
}
}
}
I just tried the below code in sales order screen and it seems working!
var props = typeof(SOOrder).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PXDecimalAttribute)));
foreach (System.Reflection.PropertyInfo item in props)
{
PXDecimalAttribute.SetPrecision(this.Base.Caches[typeof(SOOrder)], item.Name, 1);
}
You might need to change this to match your DAC.

How to clip a series by its grid?

I want to create an XYPlot such that the most left point and the most right point of all series, are clipped off.
So, let's say I want to plot the series described by the following arrays
Number[] xs = new Number[]{-1, 50, 101};
Number[] ys = new Number[]{10, 20, 20};
But I want to clip off the first point (-1,10) and the last point (101,20), how could I do it?
I tried to use the methods setDomainBoundaries() and setRangeBoundaries() but the series exceeds it's grid/plot area.
I'd suggest a custom implementation of XYSeries to do this. Here's a example that should basically do what you want:
class MyXYSeries implements XYSeries {
Number[] xs = new Number[]{-1, 50, 101};
Number[] ys = new Number[]{10, 20, 20};
#Override
public int size() {
return xs.length - 1; // clip the trailing point
}
#Override
public Number getX(int index) {
// shift xy vals over one to clip the leading point
return xs[index+1];
}
#Override
public Number getY(int index) {
// shift xy vals over one to clip the leading point
return ys[index+1];
}
#Override
public String getTitle() {
return "your title";
}
}

Is there an existing PropertyGrid UITypeEditor for type "ChartColorPalette"?

I'm trying to write a simple property grid to allow the users to modify the colours of a Chart. By default, a Chart has a "Palette" property, which is of the enumeration type "ChartColorPalette". If the object which underlies my property grid also has a "Palette" property of the same type, I get the drop-down list of possible values. What I don't get however, is the little stripey images to the left of the value names.
Now, I can write a UITypeEditor derived class and have the "PaintValue" draw little resource bitmaps which I have culled from the screen using "Paint" or somesuch, but this seems rather tedious.
Does anyone know if there is already a type editor for the "ChartColorPalette" enumeration which I can use to get the little bitmaps ?
as it happens, writing the UITypeEditor is not that tricky, and not that much code either.
Firstly I created a type editor that looked like this:
private class ChartColorPaletteEditor : UITypeEditor
{
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(PaintValueEventArgs e)
{
String paletteName = e.Value.ToString();
String baseName = this.GetType().Namespace + ".MyChart";
ResourceManager mgr = new ResourceManager(baseName, this.GetType().Assembly);
Bitmap bmp = mgr.GetObject(paletteName) as Bitmap;
if (bmp != null)
{
e.Graphics.DrawImage(bmp, e.Bounds);
bmp.Dispose();
}
}
}
I attached this to my control property in the usual way:
[DefaultValue(typeof(ChartColorPalette), "BrightPastel")]
[Editor(typeof(ChartColorPaletteEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("Appearance")]
[Description("The named palette to use when choosing the colour scheme for the chart series lines.")]
public ChartColorPalette Palette { get; set; }
Then I added a small PNG resource for each of the little palette images. I had a derived control "MyChart" which inherited from "Chart" and I added the images to that as resources (making sure to set the "Persistance" property to "Embedded in .resx" to save having to keep the PNG files about). The names of the PNG files matched the names in the ChartColorPalette enumeration.
The only issue was where to get the little 20 x 14 images from. I originally just culled them using Paint.exe but didn't like that, so I wrote some code to generate them for me. That was fairly simple, once I had found the colour values that are used by the Charting control. One subtlety is that, where there are more than 12 colours in a palette, the little bitmap uses every other colour. That code looked like this:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms.DataVisualization.Charting;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Enum.GetValues(typeof(ChartColorPalette)).OfType<ChartColorPalette>().ToList().ForEach(GeneratePNG);
}
static void GeneratePNG(ChartColorPalette palette)
{
if (palette == ChartColorPalette.None) return;
Color[] colours = palette.GetColors();
if (colours.Length >= 12)
{
colours = new Color[] { colours[0], colours[2], colours[4], colours[6], colours[8], colours[10] };
}
else
{
colours = new Color[] { colours[0], colours[1], colours[2], colours[3], colours[4], colours[5] };
}
using (Bitmap bmp = new Bitmap(20, 14))
{
using (Graphics gr = Graphics.FromImage(bmp))
{
using (SolidBrush b1 = new SolidBrush(colours[0]),
b2 = new SolidBrush(colours[1]),
b3 = new SolidBrush(colours[2]),
b4 = new SolidBrush(colours[3]),
b5 = new SolidBrush(colours[4]),
b6 = new SolidBrush(colours[5]))
{
int height = bmp.Height - 2;
gr.DrawRectangle(Pens.Black, 0, 0, bmp.Width - 1, bmp.Height - 1);
gr.FillRectangle(b1, new Rectangle(1, 1, 3, height));
gr.FillRectangle(b2, new Rectangle(4, 1, 3, height));
gr.FillRectangle(b3, new Rectangle(7, 1, 3, height));
gr.FillRectangle(b4, new Rectangle(10, 1, 3, height));
gr.FillRectangle(b5, new Rectangle(13, 1, 3, height));
gr.FillRectangle(b6, new Rectangle(16, 1, 3, height));
}
}
String path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, #"Visual Studio 2010\Projects\DataVisualization.Charting\Palette Bitmaps");
String filename = palette.ToString() + ".png";
bmp.Save(Path.Combine(path, filename), ImageFormat.Png);
}
}
}
public static class Extensions
{
public static Color[] GetColors(this ChartColorPalette value)
{
switch (value)
{
case ChartColorPalette.Berry:
return GetColors(0x8a2be2, 0xba55d3, 0x4169e1, 0xc71585, 0x0000ff, 0x8a2be2, 0xda70d6, 0x7b68ee, 0xc000c0, 0x0000cd, 0x800080);
case ChartColorPalette.Bright:
return GetColors(0x008000, 0x0000ff, 0x800080, 0x00ff00, 0xff00ff, 0x008080, 0xffff00, 0x808080, 0x00ffff, 0x000080, 0x800000, 0xff0000, 0x808000, 0xc0c0c0, 0xff6347, 0xffe4b5);
case ChartColorPalette.BrightPastel:
return GetColors(0x418cf0, 0xfcb441, 0xe0400a, 0x056492, 0xbfbfbf, 0x1a3b69, 0xffe382, 0x129cdd, 0xca6b4b, 0x005cdb, 0xf3d288, 0x506381, 0xf1b9a8, 0xe0830a, 0x7893be);
case ChartColorPalette.Chocolate:
return GetColors(0xa0522d, 0xd2691e, 0x8b0000, 0xcd853f, 0xa52a2a, 0xf4a460, 0x8b4513, 0xc04000, 0xb22222, 0xb65c3a);
case ChartColorPalette.EarthTones:
return GetColors(0xff8000, 0xb8860b, 0xc04000, 0x6b8e23, 0xcd853f, 0xc0c000, 0x228b22, 0xd2691e, 0x808000, 0x20b2aa, 0xf4a460, 0x00c000, 0x8fbc8b, 0xb22222, 0x8b4513, 0xc00000);
case ChartColorPalette.Excel:
return GetColors(0x9999ff, 0x993366, 0xffffcc, 0xccffff, 0x660066, 0xff8080, 0x0066cc, 0xccccff, 0x000080, 0xff00ff, 0xffff00, 0x00ffff, 0x800080, 0x800000, 0x008080, 0x0000ff);
case ChartColorPalette.Fire:
return GetColors(0xffd700, 0xff0000, 0xff1493, 0xdc143c, 0xff8c00, 0xff00ff, 0xffff00, 0xff4500, 0xc71585, 0xdde221);
case ChartColorPalette.Grayscale:
return GetColors(0xc8c8c8, 0xbdbdbd, 0xb2b2b2, 0xa7a7a7, 0x9c9c9c, 0x919191, 0x868686, 0x7b7b7b, 0x707070, 0x656565, 0x5a5a5a, 0x4f4f4f, 0x444444, 0x393939, 0x2e2e2e, 0x232323);
case ChartColorPalette.Light:
return GetColors(0xe6e6fa, 0xfff0f5, 0xffdab9, 0xfffacd, 0xffe4e1, 0xf0fff0, 0xf0f8ff, 0xf5f5f5, 0xfaebd7, 0xe0ffff);
case ChartColorPalette.Pastel:
return GetColors(0x87ceeb, 0x32cd32, 0xba55d3, 0xf08080, 0x4682b4, 0x9acd32, 0x40e0d0, 0xff69b4, 0xf0e68c, 0xd2b48c, 0x8fbc8b, 0x6495ed, 0xdda0dd, 0x5f9ea0, 0xffdab9, 0xffa07a);
case ChartColorPalette.SeaGreen:
return GetColors(0x2e8b57, 0x66cdaa, 0x4682b4, 0x008b8b, 0x5f9ea0, 0x3cb371, 0x48d1cc, 0xb0c4de, 0xffffff, 0x87ceeb);
case ChartColorPalette.SemiTransparent:
return GetColors(0xff6969, 0x69ff69, 0x6969ff, 0xffff69, 0x69ffff, 0xff69ff, 0xcdb075, 0xffafaf, 0xafffaf, 0xafafff, 0xffffaf, 0xafffff, 0xffafff, 0xe4d5b5, 0xa4b086, 0x819ec1);
case ChartColorPalette.None:
default:
return GetColors(0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000);
}
}
private static Color[] GetColors(params Int32[] values)
{
return values.Select(value => Color.FromArgb(255, Color.FromArgb(value))).ToArray(); // alpha channel of 255 for fully opaque
}
}
}
Hope this is useful to someone out there...

Resources