round decimals to a specific value with php - php

I am trying to make a float number e.g. 110.34 to "round" to 110.90
The thing is I am converting product prices caused by currency switcher and I want to make the values values look good.
I have somewhere the function
function($price)
which gives me the price of the product.
And I was trying to make it with the round() function e.g.
return round($price * 2, 0) / 2;
But this will round it to x.00 or x.50
Is there any other function that can round all values to x.90?

Now i made it like this?
return intval($price) + 0.90;
is this the right way, at least it looks good. :-D

Related

Setting a new variable in each multiple of 10, with no limit

i'm hoping someone can help with my question.
Let's say I have a quantity which is simply an integer in a variable. I know that if the quantity is below 10, the cost will be 1.50. Between 10-20 the cost would be 1.50 x 2, then between 20-30 the cost would be 1.50 x 3 and so on.
The bit im stuck on is the "and so on". I know how I could code this if I knew there was a limit of let's say 100, however if it can be limitless, how could I code this in an intelligent way to work it out for me?
Sorry for the example-less question. I wouldn't know where to start with this query.
Thank you for your time
Since your steps are in tenfold, you can simply divide your number by 10 to get the amount of 1.5's you'll need to calculate the cost.
Then, we'll use ceil() to round the divison to the next integer. Now, for example, 5/10 = 0,5 results in return 1.5 * 1;
Take a look at this example;
<?php
function getCost($n) {
return 1.5 * ceil($n / 10);
}
var_dump(getCost(5)); float(1.5)
var_dump(getCost(15)); float(3)
var_dump(getCost(25)); float(4.5)
var_dump(getCost(35)); float(6)
var_dump(getCost(100)); float(15)
var_dump(getCost(12345)); float(1852.5)
Try it online!

What is the correct format to use in PHP when denoting "money" attribute fetched from MySQL database?

I'm using the "number_format" function to denote money" attribute in PHP/MySQL.
The attribute itself is stored in my database.
Select account_balance from my_table where login = 'xxxxxx';
$correct_account_balance = number_format($account_balance,
['my_balance'],2); }
In other words : the denotation "2" will add two extra numbers after the decimal point, as follows : 10.00 (for example)
This code works fine............except for one small problem : if the amount after the decimal point has a zero at the end, it does not display!
For example : if the amount is, say, 10 dollars and 35 cents, it displays correctly : 10.35
However, if the amount is 10 dollars, and 30 cents, it displays as : 10.3 (instead of : 10.30 )
The reason is : my program also performs arithmetical operations on the account_balance AFTER I have converted it using the "number_format" function.
For example :
$correct_account_balance -= 0.25 (this will subtract 0.25 each time the program is executed)
This is why, anytime there is a "zero" at the end of the actual amount (like : 10.30), it displays as : 10.3
Is there anyway to get around this? Google doesn't seem to know;
The reason is : my program also performs arithmetical operations on the account_balance AFTER I have converted it using the "number_format" function.
You'll need to re-run number_format after doing the operations on it.
You really shouldn't run it at all until it's ready for display, either, the commas it adds to larger numbers will hugely mess up your calculations. As an example, the following:
<?php
$number = 100000.30;
$number = number_format($number, 2);
$number -= 0.25;
echo number_format($number, 2);
results in the output:
99.75
Which means you've just stolen $99,900.55 from your customers with a type conversion error.

Using round() to get exact value - PHP

Hey guy's I am working on a project of mine which involves the use of money. I am trying to not use round anymore because, it's rounding things to nearest tenth and I need exact numbers. One reason I was using it, was because it was giving a whole number.
The way I am working my number system is that 100 = $1, 2000 = $20, etc.. I was currently using the round function because it would get rid of the decimal point for me and give me a whole number, lets say: 223 which in turn would = $2.23.
Here is what I am using:
$amount += round(($amount / 29) + 30);
Here are the numbers:
Lets say we have a charge of 100 and we add 125 which equal 225 (USD $2.25). Now we add taxes and processing: + 2.9% + $.30. After multiplying 2.25 by 2.9% and adding .30 the amount would be: 0.36525 - this is the amount that should be added than to the $2.25 which than would be 261 = $2.61
The issue is because of the rounding, when I look in my Stripe panel (I am using Stripe API for payments) I see a charge of $2.63. So my question is, how would I go about making it exact without having any rounding and decimal places.
UPDATE:
Here is the above example more explained:
Lets say we have a charge of 100 and we add 125 which equal 225 (USD $2.25). Now we add taxes and processing: + 2.9% + $.30. After multiplying 2.25 by 2.9% and adding .30 the amount would be: 0.36525 - this is the amount that should be added than to the $2.25 which than would be 261 = $2.61
So now with that the actual value of amount that should be charged is $2.61 but instead when using the round it gives me 263 which also means $2.63. The above example is the simple math that is correct.
In order to avoid calculation hiccups like that, only round the final result. Keep all other calculations as accurate as possible:
$original = 100;
$original += 125;
$tax = $original * 2.9 / 100; //+2.9%
$tax += 30; //+$.30
$original += $tax; //Add tax.
echo $original; //Result is 261.525. Round as you please.
You can specify precision and rounding method to keep it consistent (PHP round()), then you can deal with the actual values. Doing math tricks like multiplication by a multiple of 10 will only make it more confusing in the long run.
$amount += round(($amount / 29) + 30, 2, PHP_ROUND_HALF_UP);
Will this solve your problem?

PHP - get closest number given a certain number?

I'm modifying one of OpenCart's product filters to filter products in/out by price. What I do is get all products belonging to a certain category and extract their prices to put them in a slider, but this is not elegant or 'professional' at all, and I would like to code a proper solution.
Let's say I have the following prices: 125, 270, 517, 1680 and 14790. What I would like to do (ideally) is get the highest number (14790 in this short example) and, from it, get something like '15000', so I can divide that between a given factor (like 100) and put that into a slider.
Is there a PHP function to do this kind of calculation?
If I understand your question, and you're asking to round to essentially the nearest 100, there isn't a specific function, but with a bit of maths you can round to the nearest hundred like so:
$price = ceil($price / 100) * 100;
Using:
$price = ceil($price / 1000) * 1000;
Would round to the nearest 1000.
Get the max number, then round it up to the nearest thousand?
<?php
$largest = max(125, 270, 517, 1680, 14790);
$nearest = ceil($largest / 1000) * 1000;
You could just loop through the numbers, remembering the highest value as you go. It's common coding practice. (Ok there really is a max() function as well, echo max(1, 3, 5, 6, 7); // 7)
Then you could divide the highest number by your factor, take the integer you get and add one to it, then multiply by the factor again and there you go.
just do : x=floor(14790/100) ; the floor function returns the next lowest integer value

Understanding VBScript

I have a VBScript that I`m converting to PHP, I hae some part that I don`t understand and don`t know the output of ... Also if possible, provide me with a similar method in HTML/PHP
TextBox1.Value = 1#
txtTurnoverIncl = TextBox1
Format(CDbl(txtTurnoverExcl.Text) * _
CDbl(txtRoyalty.Text) / 100, "#,##0.00")
If txtTurnoverExcl.Text <> "" Then
Format(Round(.Text * 14 / 114, 2), "#,##0.00")
TextBox1 = Now()
TextBox3 = Date
TextBox4 = Format(MyDate, "dddd")
And this function:
Private Function SumCashUp() As Double
Dim i As Long
Dim tmp As Double
For i = 10 To 12
With Me.Controls("TextBox" & i)
If IsNumeric(.Text) Then
tmp = tmp + CDbl(.Text)
End If
End With
Next i
SumCashUp = tmp
End Function
I guess thats all.
TextBox1.Value = 1# - Assign the value 1 in format Double to the textbox control. (thanks MikeD)
txtTurnoverIncl = TextBox1 - Assigning reference to the control TextBox to variable called txtTurnoverIncl
CDbl(txtTurnoverExcl.Text) - Convert the text inside the textbox txtTurnoverExcl to double i.e. numeric value with decimal point e.g. 2.6 - this is useful if you want to perform mathematical operations on the value for example.
Format(..., "#,##0.00") - Format number to look like this: 2.60 or 8.25 i.e. with two digits after decimal point.
Round(.Text * 14 / 114, 2) - The .Text means you're inside With (somecontrol) block, so it's actually somecontrol.Text i.e. taking the Text of the control. Round function will round the number for example Round(662.791, 2) will return 662.79 and Round(662.796, 2) will return 662.8
Now() - Returns the current date and time on the machine where the code is executing
Date or Date() - Like Now() but only with the date, time will be 00:00:00
Format(MyDate, "dddd") - Get name of the day of week of MyDate, according to the Culture on the machine. For example for Hebrew culture it will return יום שלישי for English culture it will return Tuesday. In general, Format() given date and string will Format the date according to the string e.g. Format(Now(), "dd/MM/yyyy") will return 14/12/2010
The last function returns the sum of the values of the textboxes named "Textbox10", "Textbox11", and "Textbox12" in a pretty complicated way. I guess in PHP you would do something like this (assuming you are POSTing a form):
function sumCashUp() {
return (double) $_POST['Textbox10'] + (double) $_POST['Textbox11'] + (double) $_POST['Textbox12'];
}
first of all it would be better to analyze what the whole thing is doing (semantically) rather than looking at sequences of code. So the remainder of this post is a bit speculative ....
There are a couple of textboxes displayed on the screen
TextBox1 ... initialized with value 1(double), later containing current time (now()) (imho a sin in itself - brrrr - hope there is good business logic explanation for this)
TextBox3 ... initialized with the current date
TextBox4 ... initialized with "something we don't know" - hopefully a date (MyDate), and formated as Weekday ("dddd")
TextBox10 - TextBox12 ... seem to be used to calculate a variable SumCashUp
we have some more variables which may be textboxes as well (as sometimes we see a .Text added in the code)
txtTurnoverIncl
txtTurnoverExcl
txtRoyalty
SumCashUp
and a code fragment that calculates a 14% margin from a Gross (*14/114), rounds and formats the result ... and we have no clue about where this result is used. We can speculate that it may be another form field (because of .Text) - maybe txtRoyalty - but we don't know.
Basically all the code fragments are about putting values into textboxes displayed on the screen and/or using the values of that text boxes to compute something (like the SumCashUp or a 14% GM).
So I guess the path to the solution must be
get the source layout of textboxes
understand the business logic
create a HTML page containing a form with similar objects (textboxes, a submit button, etc.)
write PHP code that implements the business logic - most probably as a reaction to a POST event triggered by a Submit button
You already received a couple of code fragments, but one needs to put this into a greater context, otherwise the code blocks won't help.

Categories