Retain 2 decimal points on float when converting to string delphi - string

I'm adding lines to a memo box from a sql query dataset. The data is being added using the memo1.lines.add function looping through the dataset
memo1.Clear;
frmMain.Query2.Open;
try
while not frmMain.Query2.Eof do
begin
memo1.Lines.Add(frmMain.Query2.FieldByName('mass').AsString);
frmMain.Query2.Next;
end;
finally
frmMain.Query2.Close;
end;
Everething from this point is working fine, the only problem is that because the data is being converted into string format is loses the trailing 0 .ie
Float value = 40.50 String Value = 40.5 .
Float value = 42.40 String Value = 42.4 .
Float value = 40.53 String Value = 40.53 .
Is there any way this could be rectified? FormatFloat doesn't want to format it because it's not a float anymore. StrtoInt doesn't work because of the 3 sting values in the memobox.

Instead of using AsString retrieve your values as Float values and the use FloatToStrF. E.g.
memo1.Lines.Add(FloatToStrF(frmMain.Query2.FieldByName('mass').AsFloat, ffNumber, 15, 2));

I like Format.
Format('%.2n', [frmMain.Query2.FieldByName('mass').AsFloat]);

Related

Groovy : String to float Conversion

Used code below to save value for float
domainInstance.standardScore = params["standardScore"] as float
In this case my input was given as 17.9 and in db2 database saving as 17.899999618530273 but I want to save as 17.9 itself, let me know how to do it
You can't set precision to a Float or Double in Java. You need to use BigDecimal.
domainInstance.standardScore = new BigDecimal(params["standardScore"]).setScale(1, BigDecimal.ROUND_HALF_UP);
The method BigDecimal.setScale(1, ...) limits decimal to one place only. The second parameter is the rounding strategy.
You need to use BigDecimal to do Conversion from String, then BigDecimal(value).floatValue() to get float, You can do this on more that one way, examples
1 - Using setScale in BigDecimal
def temp = new BigDecimal(params["standardScore"]).setScale(1, BigDecimal.ROUND_HALF_UP)
2- Using DecimalFormat
DecimalFormat df = new DecimalFormat("#.0");
def temp = new BigDecimal(df.format(params["standardScore"] ))
Then you need to get the float value
domainInstance.standardScore = temp.floatValue()

How to add two decimal numbers

I have three edit texts in which if I put decimal numbers like 23.5 +23.5 and click calculate the app crashes and if I put 235000 +235000 it gives correct results what should be the correct codes for decimal number ,I am new to all this please forgive me for my mistakes`
#TargetApi(Build.VERSION_CODES.N)
public void onButtonClick(View v){
double tys=Integer.parseInt(Tys.getText().toString());
double lys=Integer.parseInt(Lys.getText().toString());
double tgt=Integer.parseInt(Tgt.getText().toString());
double sum=((int)tys-lys)/lys*100;
DecimalFormat precision = new DecimalFormat("0.0");
// dblVariable is a number variable and not a String in this case
GrowthResult.setText(precision.format(sum)+"%");
double sum2 =((int)tys/tgt)*100;
achievementResult.setText(precision.format(sum2)+"%");
double sum3 =((int)tys-lys);
JumpResult.setText(precision.format(sum3));
`
You can take data types like float type.then you will get correct answer
float a;
float b;
Edit text data parse in float type then you will get correct answer

Powershell: convert string to number

I have an Array where some drive data from WMI are captured:
$drivedata = $Drives | select #{Name="Kapazität(GB)";Expression={$_.Kapazität}}
The Array has these values (2 drives):
#{Kapazität(GB)=1.500} #{Kapazität(GB)=1.500}
and just want to convert the 1.500 into a number 1500
I tried different suggestions I found here, but couldn't get it working:
-Replace ".","" and [int] doesn't work.
I am not sure if regex would be correct and how to do this.
Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.
$a = 15; $b = 2; $a + $b --> 152
But if you divide it before:
$a/1 + $b/1 --> 17
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
Replacing the "." character when value is a string
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
Converting the string value to an integer
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.
function universalToDate
{
param (
$paramValue
)
$retVal=""
if ($paramValue)
{
$epoch=[datetime]'1/1/1970'
[long]$returnedLong = 0
[bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
if ($result -eq 1)
{
$val=$returnedLong/1000.0
$retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
}
}
else
{
$retVal=$null
}
return($retVal)
}
Replace all but the digits in the string like so:
$messyString = "Get the integer from this string: -1.500 !!"
[int]$myInt = $messyString -replace '\D', ''
$myInt
# PS > 1500
The regex \D will match everything except digits and remove them from your string.
This will work fine for your example.
It seems the issue is in "-f ($_.Partition.Size/1GB)}}" If you want the value in MB then change the 1GB to 1MB.

Inconsistent behavior with (relatively simple) UDF returning a string result

I'm writing a function that UNINTENTIONALLY seems to work differently depending on how it is invoked.
The function should do the following:
ACCEPT 2 parameters, a string and an integer
Return 1 string of variable length that might be any length from 1 to several thousand characters.
If the string is null, the function returns a string of spaces equal to the integer param.
If the string is shorter than the length, it will pad the string to the desired length.
If the string is longer than the length, it will return a cropped string.
If the string is the correct length, it will return the string.
The input string and the output string should work for any string variable, regardless of length.
USE [mydb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fix_len]
(
#v varchar(max),
#len_v int
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #cur_len as int
DECLARE #ret_val as varchar(max)
set #ret_val = ISNULL(#v, space(#len_v))
set #cur_len = dataLENgth(#ret_val)
set #ret_val = case when #cur_len < #len_v then #ret_val + SPACE(#len_v-#cur_len)
when #cur_len > #len_v then SUBSTRING(#ret_val,1, #len_v)
else #ret_val
end
RETURN #ret_val
END
Now here's the problem. IF I invoke this function like this:
SELECT dbo.fix_len(a, 10) + dbo.fix_len(b, 10) + dbo.fix_len(c, 10) + dbo.fix_len(d, 10) from sometable
THEN it (the fix_len function) works JUST FINE!
However, if I invoke it like this:
SELECT dbo.fix_len(a, 10), dbo.fix_len(b, 10), dbo.fix_len(c, 10), dbo.fix_len(d, 10) from sometable
THEN it (the fix_len function or maybe sql server) wants to pad each field out to max chars.
The current purpose of this for me at the current time is to create a text file that concatenates the fields together. I invoke a stored procedure through the bcp command (in the cmd shell). It works fine, IF I MANUALLY CONCATENATE THE STRINGS MYSELF as in the first select.
However, if I let BCP figure it out, it pads each field out. But I don't think BCP is the problem. If I just execute each of the two selects from a query window, the first select is right - the second adds the padding.
Any ideas what I'm doing wrong - and just as importantly, what I can do to fix it?

Arduino issue: String to float adds two zeros instead of the correct integer

Code snippet:
Serial.println(sensorString); //so you can see the captured string
char carray[sensorString.length() + 1]; //determine size of the array
Serial.println(sizeof(carray));
sensorString.toCharArray(carray, sizeof(carray)); //put sensorString into an array
float sensorStringFloat = atoi(carray); //convert the array into an Integer
Serial.println(sensorStringFloat);
Serial.println(sensorStringFloat) prints out 5.00 instead of the correct float value of 5.33. Why is that and how do I fix this issue? I would eventually like to pass sensorStringFloat over to:
aJson.addNumberToObject(sensor, "ph", sensorStringFloat);
atoi converts a numeral in ASCII to an integer. The comment on that line also says it converts to an integer. So you got an integer result, 5. To convert to floating-point, consider using atof. (Note that “f” stands for floating-point, not “float”. atof returns a double.)
you should pass another parameter which defines the format, in this case it is the number of digits after the floating point.
Serial.println(sensorString,2);
String temp = String (_float, 0);
say float x;
convert to String using
String _temp = String(x, 0);
The second parameter 0... says i want no trailing zeros.
Caution: However this is only suitable for whole numbers.
This solution would not work for say... 1.24
You'll get just 1.

Resources