List of usage examples for java.text DecimalFormatSymbols setDecimalSeparator
public void setDecimalSeparator(char decimalSeparator)
From source file:Main.java
public static void main(String args[]) { double d = 123456.7890; DecimalFormat df = new DecimalFormat("#####0.00"); DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs);/*from w ww. ja v a 2 s . c o m*/ System.out.println(df.format(d)); }
From source file:com.enitalk.controllers.paypal.Usd.java
public static void main(String[] args) throws IOException, ParseException { String rs = Request.Get("http://www.cbr.ru/scripts/XML_daily.asp") .addHeader("Content-type", "application/xml;charset=utf-8").execute().returnContent() .asString(Charset.forName("windows-1251")); Pair<AutoPilot, VTDNav> bb = getNavigator(rs.getBytes()); String change = getChange(bb.getLeft(), bb.getRight()); System.out.println("Rs " + change); DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(','); df.setDecimalFormatSymbols(symbols); BigDecimal dd = BigDecimal.valueOf(df.parse(change).doubleValue()).setScale(2, RoundingMode.CEILING); System.out.println("Dd " + dd); }
From source file:DecimalFormatDemo.java
static public void main(String[] args) { customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); customFormat("\u00a5###,###.###", 12345.67); Locale currentLocale = new Locale("en", "US"); DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale); unusualSymbols.setDecimalSeparator('|'); unusualSymbols.setGroupingSeparator('^'); String strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4);/*from w w w . j a v a 2 s . c o m*/ String bizarre = weirdFormatter.format(12345.678); System.out.println(bizarre); Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"), new Locale("fr", "FR") }; for (int i = 0; i < locales.length; i++) { localizedFormat("###,###.###", 123456.789, locales[i]); } }
From source file:fr.cs.examples.attitude.EarthObservation.java
/** Program entry point. * @param args program arguments (unused here) *///from w w w . ja v a 2 s . co m public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); final SortedSet<String> output = new TreeSet<String>(); // Initial state definition : date, orbit final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC()); final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity), FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU); // Attitudes sequence definition final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0); final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH); final PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth(); final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final AttitudesSequence attitudesSequence = new AttitudesSequence(); final AttitudesSequence.SwitchHandler switchHandler = new AttitudesSequence.SwitchHandler() { public void switchOccurred(AttitudeProvider preceding, AttitudeProvider following, SpacecraftState s) { if (preceding == dayObservationLaw) { output.add(s.getDate() + ": switching to night law"); } else { output.add(s.getDate() + ": switching to day law"); } } }; attitudesSequence.addSwitchingCondition(dayObservationLaw, nightRestingLaw, dayNightEvent, false, true, 10.0, AngularDerivativesFilter.USE_R, switchHandler); attitudesSequence.addSwitchingCondition(nightRestingLaw, dayObservationLaw, nightDayEvent, true, false, 10.0, AngularDerivativesFilter.USE_R, switchHandler); if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) { // initial position is in daytime attitudesSequence.resetActiveProvider(dayObservationLaw); } else { // initial position is in nighttime attitudesSequence.resetActiveProvider(nightRestingLaw); } // Propagator : consider the analytical Eckstein-Hechler model final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence, Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU, Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40, Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60); // Register the switching events to the propagator attitudesSequence.registerSwitchEvents(propagator); propagator.setMasterMode(180.0, new OrekitFixedStepHandler() { public void init(final SpacecraftState s0, final AbsoluteDate t) { } public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException { try { DecimalFormatSymbols angleDegree = new DecimalFormatSymbols(Locale.US); angleDegree.setDecimalSeparator('\u00b0'); DecimalFormat ad = new DecimalFormat(" 00.000;-00.000", angleDegree); // the Earth position in spacecraft frame should be along spacecraft Z axis // during nigthtime and away from it during daytime due to roll and pitch offsets final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO); final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K); // the g function is the eclipse indicator, its an angle between Sun and Earth limb, // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb final double eclipseAngle = dayNightEvent.g(currentState); output.add(currentState.getDate() + " " + ad.format(FastMath.toDegrees(eclipseAngle)) + " " + ad.format(FastMath.toDegrees(pointingOffset))); } catch (OrekitException oe) { throw new PropagationException(oe); } } }); // Propagate from the initial date for the fixed duration SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(12600.)); // we print the lines according to lexicographic order, which is chronological order here // to make sure out of orders calls between step handler and event handlers don't mess things up for (final String line : output) { System.out.println(line); } System.out.println("Propagation ended at " + finalState.getDate()); } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }
From source file:fmiquerytest.Coordinates.java
public static void main(String[] args) { df_short.setTimeZone(tz); df_iso.setTimeZone(tz);// ww w. j a v a2 s. c o m df_daycode.setTimeZone(tz); DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(); otherSymbols.setDecimalSeparator('.'); df_fiveDecimal.setDecimalFormatSymbols(otherSymbols); String startTime = df_short.format(new Date(startTimeMillis)); System.out.println("startTime: " + startTime); //Clean up old weather data //********************************************************************** FileSystemTools.cleanupOldWeatherData(daysToStoreWeatherData); //Google query //********************************************************************** if (gShare.equals("")) { Scanner input = new Scanner(System.in); System.out.println("Paste Google Directions Share:"); gShare = input.nextLine(); } String gQuery = Parser.getQueryFromShare(gShare); System.out.println("Google query URL: " + gQuery); //Check if we already have this route //Valid only if the route option is 0 (default) //Because otherwise we cannot be sure we already have the optional route List<routeStep> gSteps = new ArrayList<>(); if (FileSystemTools.isSavedRoute(gQuery) && gRouteOption == 0) { System.out.println("Route found from saved list. Loading."); gSteps = FileSystemTools.loadSavedRoute(gQuery); } else { gSteps = Parser.getSteps(gQuery); if (gRouteOption == 0) { System.out.println("Saving new route to list."); FileSystemTools.saveRoute(gQuery, gSteps); } } //Compile route table with current settings //********************************************************************** List<routeStep> routeData = RouteTools.compileRoute(gSteps, refreshInterval); String endTime = df_short.format(new Date(startTimeMillis + routeDur * 1000)); System.out.println("endTime: " + endTime); //Forecast from FMI is only for 48h - warning if we are going over //Or is it 54h? http://ilmatieteenlaitos.fi/avoin-data-saaennustedata-hirlam if (((startTimeMillis + routeDur * 1000) - System.currentTimeMillis()) / (1000 * 60 * 60) > 48) { System.out.println("**************************************************" + newLine + "WARNING:" + newLine + "Weather forecast available only for 48 hours" + newLine + "**************************************************"); } //Prepare time and file variables //********************************************************************** String nowAsISO = df_iso.format(new Date()); System.out.println("Start ISO time: " + nowAsISO); double timeMarginal = routeDur * 1.2 + 3600; String endTimeForFmi = df_iso.format(new Date(startTimeMillis + (intValue(timeMarginal)) * 1000)); String endTimeForFile = df_iso.format(new Date(startTimeMillis + (intValue(routeDur + 3600)) * 1000)); System.out.println("End ISO time: " + endTimeForFmi); String fmiParam = new StringBuilder("&starttime=").append(nowAsISO).append("&endtime=") .append(endTimeForFmi).toString(); File weatherDataFileNameFirst = new File("weather" + nowAsISO.replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); File weatherDataFileNameLast = new File("weather" + endTimeForFmi.replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); File weatherDataFileNameStart = new File( "weather" + (df_iso.format(new Date(startTimeMillis))).replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); File weatherDataFileNameEnd = new File("weather" + endTimeForFile.replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); List<stationData> allStations = new ArrayList<>(); List<stationData> fmiData = new ArrayList<>(); List<String> savedFileTimes = new ArrayList<>(); //********************************************************************** //Check if we already have the weather data //********************************************************************** if (!weatherDataFileNameStart.exists() || !weatherDataFileNameEnd.exists()) { //FMI query //********************************************************************** String fmiCities = new StringBuilder(fmiBase).append(fmiKey).append(fmiMiddle).append(fmiQueryCities) .append(fmiParam).toString(); String fmiObsStations = new StringBuilder(fmiBase).append(fmiKey).append(fmiMiddle) .append(fmiQueryObsStations).append(fmiParam).toString(); //System.out.println("FMI cities URL: "+fmiCities); //System.out.println("FMI obsstations URL: "+fmiObsStations); //Collect weather data from FMI //********************************************************************** System.out.print("FMI data:" + newLine + fmiCities + newLine + "Loading and processing..."); fmiData.addAll(Parser.getStations(fmiCities)); System.out.println("SUCCESS."); System.out.print("FMI data:" + newLine + fmiObsStations + newLine + "Loading and processing..."); fmiData.addAll(Parser.getStations(fmiObsStations)); System.out.println("SUCCESS."); //Get unique stations //********************************************************************** List<stationData> uniqueStations = ToolBox.getUniqueStations(fmiData); System.out.println("Parsed stations count: " + uniqueStations.size()); //Save or load stations //********************************************************************** List<stationData> savedStations = new ArrayList<>(); if (!stationFileName.exists()) { //Save current parsed stations to file FileSystemTools.saveObjectToFile(uniqueStations, stationFileName); } else { //Or if the stations were already saved, load them System.out.println("Station information file found: " + stationFileName); System.out.print("Loading..."); savedStations = FileSystemTools.loadStationsFromFile(stationFileName); System.out.println("DONE."); System.out.println("Loaded stations count: " + savedStations.size()); } //Merge station information //********************************************************************** System.out.println("Merging station information."); savedStations.addAll(uniqueStations); allStations = ToolBox.getUniqueStations(savedStations); System.out.println("Merged stations count: " + allStations.size()); //Find names for stations //********************************************************************** String gMapsGeoCode = "https://maps.googleapis.com/maps/api/geocode/xml?latlng="; //for (stationData station : allStations){ for (int i = 0; i < allStations.size(); i++) { if (allStations.get(i).stationName.equals("")) { gQuery = new StringBuilder(gMapsGeoCode).append(allStations.get(i).stationLocation.Lat) .append(",").append(allStations.get(i).stationLocation.Lon).append("&key=").append(gKey) .toString(); System.out.println("Google query URL: " + gQuery); allStations.get(i).stationName = Parser.getStationName(gQuery); } } //System.out.println("Station names parsed."); Collections.sort(allStations); //Print stations and separate them for saving //********************************************************************** List<stationData> onlyStations = new ArrayList<>(); //int indeksi = 0; List<weatherData> weatherPoint = new ArrayList<>(); weatherPoint.add(0, new weatherData("", "", "")); for (stationData station : allStations) { //System.out.format("%-4s%-30s%-10s%-10s%n", // indeksi,station.stationName,station.stationLocation.Lat,station.stationLocation.Lon); //++indeksi; onlyStations.add(new stationData(station.stationLocation, station.stationName, weatherPoint)); } //Save station names //********************************************************************** System.out.println("Saving station names."); FileSystemTools.saveObjectToFile(onlyStations, stationFileName); //Save weather dataset //********************************************************************** //Compute file names between start and end System.out.println("Saving weather data..."); long currentTimeAsDouble = System.currentTimeMillis(); int hoursPassed = intValue(Math.floor(currentTimeAsDouble - startTimeMillis) / 1000 / 60 / 60); File weatherDataFileNameTemp = weatherDataFileNameFirst; while (!weatherDataFileNameTemp.equals(weatherDataFileNameLast)) { String savedFileTime = df_iso.format(new Date(startTimeMillis + ((hoursPassed * 3600) * 1000))); savedFileTimes.add(savedFileTime); weatherDataFileNameTemp = new File( "weather" + savedFileTime.replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); //System.out.println("Weather data file: "+weatherDataFileNameTemp); //This if we don't actually maybe want //if (!weatherDataFileNameTemp.exists()){ List<stationData> thisHourWeather = FileSystemTools.extractHourOfWeatherData(savedFileTime, fmiData); //System.out.println("Saving: "+weatherDataFileNameTemp); FileSystemTools.saveObjectToFile(thisHourWeather, weatherDataFileNameTemp); //} ++hoursPassed; } } //If we have weather data saved, definitely we have the stations also //********************************************************************** else { System.out.println("Loading weather data..."); File weatherDataFileNameTemp = weatherDataFileNameStart; int hoursPassed = 0; while (!weatherDataFileNameTemp.equals(weatherDataFileNameEnd)) { String savedFileTime = df_iso.format(new Date(startTimeMillis + ((hoursPassed * 3600) * 1000))); savedFileTimes.add(savedFileTime); weatherDataFileNameTemp = new File( "weather" + savedFileTime.replaceAll("[^A-Za-z0-9 ]", "") + ".txt"); System.out.println("Weather data file: " + weatherDataFileNameTemp); if (weatherDataFileNameTemp.exists()) { fmiData.addAll(FileSystemTools.loadStationsFromFile(weatherDataFileNameTemp)); } ++hoursPassed; } allStations = FileSystemTools.loadStationsFromFile(stationFileName); System.out.println("DONE."); } //Find closest weather stations in route points and extract their data //********************************************************************** System.out.println("Calculating nearest stations in route points:"); List<Integer> neededStations = new ArrayList<>(); for (routeStep step : routeData) { distance[] stationDistances = RouteTools.calculateStationDistances(step.StartLocation, allStations); System.out.format("%-6s%.5f, %.5f ", "Step: ", step.StartLocation.Lat, step.StartLocation.Lon); for (int i = 0; i < 1; i++) { System.out.format("%-9s%-5s%-20s%.5f%n", "Station: ", stationDistances[i].stationNum, allStations.get(stationDistances[i].stationNum).stationName, stationDistances[i].stationDistance); } neededStations.add(stationDistances[0].stationNum); } System.out.println("Needed stations: " + neededStations.toString().trim()); //Remove duplicates from needed stations list Set<Integer> uniqueEntries = new HashSet<Integer>(neededStations); //Extract weather data from needed stations Map routeWeather = Collections.synchronizedMap(new HashMap()); routeWeather = WeatherTools.extractNeededStations(uniqueEntries, fmiData, allStations); //Find what fields we have List<String> allParameters = new ArrayList<>(); for (int i = 0; i < fmiData.size(); ++i) { allParameters.add(fmiData.get(i).weatherData.get(0).parameterName); } Set<String> uniqueParameters = new HashSet<String>(allParameters); for (String par : uniqueParameters) { for (Integer num : uniqueEntries) { for (String time : savedFileTimes) { //System.out.format("%-5s%-25s%-35s%s%n",num,time,par,routeWeather.get(num+"-"+time+"-"+par)); } } } // Build the final data table //********************************************************************** List<stepWeather> stepDataBase = new ArrayList<>(); stepDataBase = RouteTools.combineRouteDatabase(routeData, neededStations, allStations); //Find sunrise and sunset times during the route //********************************************************************** List<String> sunEvents = DayLightTime.calculateSunEvents(stepDataBase); for (String s : sunEvents) { System.out.println(s.replaceAll(",", ".")); } //Make a webpage to show the weather data //********************************************************************** WeatherTools.makeResultHtml(stepDataBase, allStations, routeWeather, sunEvents); }
From source file:Main.java
public static String formatBalance(BigDecimal balance, String curr, boolean round, DecimalFormat format) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator(','); dfs.setGroupingSeparator(' '); DecimalFormat currency = format; if (currency == null) { if (!round) { currency = new DecimalFormat("#,##0.00 "); } else {/*from www . j a v a 2 s . com*/ currency = new DecimalFormat("#,##0 "); } } currency.setDecimalFormatSymbols(dfs); return currency.format(balance.doubleValue()) + curr; }
From source file:Main.java
public static DecimalFormat createDecimalFormat(int minInt, int maxInt, int minFract, int maxFract, char separator, RoundingMode mode) { DecimalFormat format = (DecimalFormat) DecimalFormat.getNumberInstance(); format.setRoundingMode(mode);/*from w w w . jav a2 s. c om*/ format.setMaximumFractionDigits(maxFract); format.setMinimumFractionDigits(minFract); format.setMaximumIntegerDigits(maxInt); format.setMinimumIntegerDigits(minInt); DecimalFormatSymbols decimalSymbolComma = new DecimalFormatSymbols(); decimalSymbolComma.setDecimalSeparator(separator); format.setDecimalFormatSymbols(decimalSymbolComma); format.setGroupingUsed(false); return format; }
From source file:Main.java
private static void updateDecimalSeparator(DecimalFormat numberFormat) { DecimalFormatSymbols symbol = numberFormat.getDecimalFormatSymbols(); if (symbol.getDecimalSeparator() != DECIMAL_SEPARATOR) { symbol.setDecimalSeparator(DECIMAL_SEPARATOR); numberFormat.setDecimalFormatSymbols(symbol); }//from w w w . j a va2 s. c o m }
From source file:org.techytax.helper.AmountHelper.java
public static String formatWithEuroSymbol(BigInteger amount) { DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN); otherSymbols.setDecimalSeparator(','); otherSymbols.setGroupingSeparator('.'); DecimalFormat df = new DecimalFormat(" ###,###,###,##0", otherSymbols); return df.format(amount.doubleValue()); }
From source file:org.techytax.helper.AmountHelper.java
public static String formatWithEuroSymbol(BigDecimal amount) { DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMAN); otherSymbols.setDecimalSeparator(','); otherSymbols.setGroupingSeparator('.'); DecimalFormat df = new DecimalFormat(" ###,###,###,##0.00", otherSymbols); return df.format(amount.doubleValue()); }